def open(self): """Open model. Return True if successful, False if failed.""" if not self._open: try: RtlabApi.OpenProject(self._projectPath) logging.info('Project <{}> opened successful.'.format(self.project)) self._open = True except: logging.error("Failed to open to project <{}> model <{}> in path <{}>".format(self.project, self.model, self._projectPath)) self.update_states() return self._open
def resetModel(projectPath, reset): """ Function to force reset of running OPAL-RT model. This function is used to force a reset of the model. This is just for manually testing that resetting the model will trigger a recompilation. Otherwise we will have to log off and log on to trigger recompilation. This function will be removed in production code. :param projectPath: Path to the project file :param reset: Flag to activate a reset of the model """ if (reset): projectName = os.path.abspath(projectPath) log.info("=====Path to the project={!s}".format(projectName)) ## Open a model using its name. RtlabApi.OpenProject(projectName) log.info( "=====The connection with {!s} is completed.".format(projectName)) ## Get the model state and the real time mode modelState, realTimeMode = RtlabApi.GetModelState() ## Print the model state log.info("=====The model state is {!s}.".format( RtlabApi.OP_MODEL_STATE(modelState))) ## If the model is running if modelState == RtlabApi.MODEL_RUNNING: #print("This is the output value={!s}".format(RtlabApi.GetSignalsByName('sm_computation.reference_out'))) ## Pause the model log.info("=====The model is running and will be reset.") ctlr = 1 RtlabApi.GetSystemControl(ctlr) RtlabApi.Reset() ctlr = 0 RtlabApi.GetSystemControl(ctlr) # Return an internal defined code to avoid recompilation. RtlabApi.Disconnect() return -2222
def connectToModel(project, model): """Takes the name of the project and model to connect to(string) and connectsif model is compiled""" # project = 'ephasorex1' # model = 'phasor01_IEEE39' # connect to the local project projectPath = 'C:/RT-LABv11_Workspace_New/' projectName = os.path.join(projectPath, str(project) + '/' + str(project) + '.llp') modelPath = os.path.join(projectPath, str(project) + '/simulink/') modelName = str(model) + '.mdl' # Connects to Project try: RtlabApi.OpenProject(projectName) # modelState,realTimeMode = OpalApiPy.GetModelState() except: logging.error("<Missed Connection>") return False return True
def Load(self): try: print self.projectName instanceID=RtlabApi.OpenProject(self.projectName) print instanceID # Setting the current model in case project has multiple models instanceID=RtlabApi.SetCurrentModel(self.modelName)[0] print instanceID modelState=RtlabApi.GetModelState()[0] if modelState == RtlabApi.MODEL_LOADABLE: RtlabApi.Load(self.realTimeMode, self.timeFactor) print "Loading done." while 1: # check if the model is in the paused state after loading modelState=RtlabApi.GetModelState()[0] if modelState== RtlabApi.MODEL_PAUSED: print "Model has been loaded and paused." break except Exception as e: print "Error in loading the model:",str(e)
def compileAndInstantiate(projectPath, reset): """ Function to compile, load, and execute a model. :param projectPath: Path to the project file. """ import subprocess # Start the MetaController tasklist = subprocess.check_output('tasklist', shell=True) if not "MetaController.exe" in tasklist: log.info("=====compileAndInstantiate(): Starting the MetaController.") try: subprocess.Popen("MetaController") except: log.error( "=====compileAndInstantiate(): MetaController.exe couldn't be started. " ) log.error( "=====compileAndInstantiate(): Check that the \\common\\bin folder of RT-Lab is on the system PATH." ) raise log.info( "=====compileAndInstantiate(): MetaController is successfully started." ) # Wait to give time to the MetaController to start sleep(TIMEOUT) projectName = os.path.abspath(projectPath) log.info("=====compileAndInstantiate(): Path to the project={!s}".format( projectName)) ## Open a model using its name. RtlabApi.OpenProject(projectName) log.info( "=====compileAndInstantiate(): The connection with {!s} is completed.". format(projectName)) # reset the model so it can be recompiled. if reset: resetModel(projectPath, reset) return log.info("The model Stoptime={!s}".format(RtlabApi.GetStopTime())) # Check if model was already compiled and is already running try: ## Get the model state and the real time mode modelState, realTimeMode = RtlabApi.GetModelState() ## Print the model state log.info( "=====compileAndInstantiate(): The model state is {!s}.".format( RtlabApi.OP_MODEL_STATE(modelState))) # If the model is paused, execute it if modelState == RtlabApi.MODEL_PAUSED: ctlr = True RtlabApi.GetSystemControl(ctlr) #log.info ("=====The system control is acquired.") timeFactor = 1 RtlabApi.Execute(timeFactor) ctlr = False RtlabApi.GetSystemControl(ctlr) ## If the model is running if modelState == RtlabApi.MODEL_RUNNING: #log.info("=====The signal description of the model={!s}".format(RtlabApi.GetSignalsDescription())) #print("This is the output value={!s}".format(RtlabApi.GetSignalsByName('sm_computation.reference_out'))) ## Pause the model log.info( "=====compileAndInstantiate(): The model is running and won't be recompiled." ) # Return an internal defined code to avoid recompilation. RtlabApi.Disconnect() return -1111 except Exception: ## Ignore error 11 which is raised when ## RtlabApi.DisplayInformation is called whereas there is no ## pending message info = sys.exc_info() if info[1][0] != 11: # 'There is currently no data waiting.' ## If a exception occur: stop waiting log.error( "=====compileAndInstantiate(): An error occured during compilation." ) #raise start = datetime.now() mdlFolder, mdlName = RtlabApi.GetCurrentModel() mdlPath = os.path.join(mdlFolder, mdlName) try: ## Registering this thread to receive all messages from the controller ## (used to display compilation log into python console) RtlabApi.RegisterDisplay(RtlabApi.DISPLAY_REGISTER_ALL) ## Set attribute on project to force to recompile (optional) modelId = RtlabApi.FindObjectId(RtlabApi.OP_TYPE_MODEL, mdlPath) RtlabApi.SetAttribute(modelId, RtlabApi.ATT_FORCE_RECOMPILE, True) ## Launch compilation compilationSteps = RtlabApi.OP_COMPIL_ALL_NT | RtlabApi.OP_COMPIL_ALL_LINUX RtlabApi.StartCompile2((("", compilationSteps), ), ) log.info("=====compileAndInstantiate(): Compilation started.") ## Wait until the end of the compilation status = RtlabApi.MODEL_COMPILING while status == RtlabApi.MODEL_COMPILING: try: ## Check status every 0.5 second sleep(0.5) ## Get new status ## To be done before DisplayInformation because ## DisplayInformation may generate an Exception when there is ## nothing to read status, _ = RtlabApi.GetModelState() ## Display compilation log into Python console _, _, msg = RtlabApi.DisplayInformation(1) while len(msg) > 0: log.info(msg), _, _, msg = RtlabApi.DisplayInformation(1) except Exception: ## Ignore error 11 which is raised when ## RtlabApi.DisplayInformation is called whereas there is no ## pending message info = sys.exc_info() if info[1][0] != 11: # 'There is currently no data waiting.' ## If a exception occur: stop waiting log.error( "=====compileAndInstantiate(): An error occured during compilation." ) raise ## Because we use a comma after print when forward compilation log into ## Python log we have to ensure to write a carriage return when ## finished. log.info('') ## Get project status to check is compilation succeed status, _ = RtlabApi.GetModelState() if status == RtlabApi.MODEL_LOADABLE: log.info("=====compileAndInstantiate(): Compilation success.") else: log.error("=====compileAndInstantiate(): Compilation failed.") ## Load the current model realTimeMode = RtlabApi.SIM_MODE # Also possible to use SIM_MODE, SOFT_SIM_MODE, SIM_W_NO_DATA_LOSS_MODE or SIM_W_LOW_PRIO_MODE # realTimeMode are HARD_SYNC_MODE for hardware synchronization. An I/O board is required # on the target. SIM_MODE for simulation as fast as possible, SOFT_SIM_MODE for # soft synchronization mode. Other modes ae not relevant but can be found in Enumeration and defined # under OP_REALTIME_MODE timeFactor = 1 RtlabApi.Load(realTimeMode, timeFactor) ## Wait until the model is loaded #load_time = TIMEOUT #hard-coded minimum time for loading a model sleep(TIMEOUT) # status, _ = RtlabApi.GetModelState() # while status != RtlabApi.MODEL_LOADED: # load_time = load_time + TIMEOUT # sleep(load_time) # status, _ = RtlabApi.GetModelState() # log.info("The model is loaded. Time required={!s}".format(load_time)) try: # Get an write the signal in the models log.info("=====The signal description of the model={!s}".format( RtlabApi.GetSignalsDescription())) ## Execute the model RtlabApi.Execute(timeFactor) log.info("=====compileAndInstantiate(): The model has executed.") status, _ = RtlabApi.GetModelState() log.info("=====compileAndInstantiate(): The model state is {!s}.". format(RtlabApi.OP_MODEL_STATE(modelState))) except Exception: ## Ignore error 11 which is raised when ## RtlabApi.DisplayInformation is called whereas there is no ## pending message info = sys.exc_info() if info[1][0] != 11: # 'There is currently no data waiting.' ## If a exception occur: stop waiting log.error( "compileAndInstantiate(): An error occured during execution." ) raise end = datetime.now() log.info( '=====compileAndInstantiate(): Compiled, loaded and executed the model for the first time in {!s} seconds.' .format((end - start).total_seconds())) finally: ## Always disconnect from the model when the connection is completed log.info( "=====compileAndInstantiate(): The model has been successfully compiled and is now running." ) #fixme It seems like I shouldn't disconnect when used with ephasorsim status, _ = RtlabApi.GetModelState() log.info( "=====compileAndInstantiate(): The final model state is {!s}.". format(RtlabApi.OP_MODEL_STATE(modelState))) RtlabApi.Disconnect()
def getData(projectPath, outputNames, simulationTime): """ Function to exchange data with a running model. :param projectPath: Path to the project file. :param outputNames: Output signal names of the model. :param simulationTime: Model simulation time. """ # Wait prior to getting the outputs sleep(TIMEOUT) ## Connect to a running model using its name. projectName = os.path.abspath(projectPath) #log.info("=====Path to the project={!s}".format(projectName)) start = datetime.now() RtlabApi.OpenProject(projectName) if (simulationTime < RtlabApi.GetStopTime() or RtlabApi.GetStopTime() <= 0.0): #log.info ("=====The connection with {!s} is completed.".format(projectName)) try: ## Get the model state and the real simulationTime mode modelState, realTimeMode = RtlabApi.GetModelState() ## Print the model state log.info("=====getData(): The model state is {!s}.".format( RtlabApi.OP_MODEL_STATE(modelState))) ## If the model is running if modelState == RtlabApi.MODEL_RUNNING: ## Exchange data try: ctlr = True RtlabApi.GetSystemControl(ctlr) #log.info ("=====The system control is acquired.") RtlabApi.Pause() #log.info ("=====The model is paused.") s = "=====getData(): outputs to be get are={!s}".format( outputNames) log.info(s) #RtlabApi.GetSignalControl(True) outputValues = RtlabApi.GetSignalsByName(outputNames) timeFactor = 1 RtlabApi.Execute(timeFactor) log.info("=====getData(): The model is executed.") ## Release signal control after changing values ctlr = False RtlabApi.GetSystemControl(ctlr) #log.info ("=====The system control is released.") except Exception: ## Ignore error 11 which is raised when ## RtlabApi.DisplayInformation is called whereas there is no ## pending message info = sys.exc_info() if info[1][ 0] != 11: # 'There is currently no data waiting.' ## If a exception occur: stop waiting log.error ("=====getData(): An error occured at simulationTime={!s} while getting the " \ "output values for the output names={!s}.".format(simulationTime, outputNames)) raise ## if the model is not running else: ## Print the model state log.error( "=====getData(): The model is not running. Simulation will be terminated." ) raise end = datetime.now() log.info( '=====getData(): Get values={!s} of outputs with names={!s} in {!s} seconds.' .format(outputValues, outputNames, (end - start).total_seconds())) finally: ## Always disconnect from the model when the connection ## is completed RtlabApi.Disconnect() return outputValues else: ctlr = True #RtlabApi.GetSystemControl (ctlr) #RtlabApi.Reset() ctlr = False #RtlabApi.GetSystemControl (ctlr) RtlabApi.Disconnect() log.info ("=====getData(): The simulation stoptime={!s} is reached. "\ "The model is reset and the connection is closed.".format(RtlabApi.GetStopTime())) return zeroOutputValues(outputNames)
def setData(projectPath, inputNames, inputValues, simulationTime): """ Function to exchange data with a running model. :param projectPath: Path to the project file. :param inputNames: Input signal names of the model. :param inputValues: Input signal values of the model. :param simulationTime: Model simulation time. """ # Wait prior to setting the inputs sleep(TIMEOUT) projectName = os.path.abspath(projectPath) #log.info("=====Path to the project={!s}".format(projectName)) start = datetime.now() RtlabApi.OpenProject(projectName) if (simulationTime < RtlabApi.GetStopTime() or RtlabApi.GetStopTime() <= 0.0): #log.info ("=====The connection with {!s} is completed.".format(projectName)) try: ## Get the model state and the real simulationTime mode modelState, realTimeMode = RtlabApi.GetModelState() ## If the model is running if modelState == RtlabApi.MODEL_RUNNING: ## Set input data ########Setting inputs of the model try: #signalNames = (signalName1, signalName2, ...) #signalValues = (value1, value2, ...) #RtlabApi.SetSignalsByName(signalNames, signalValues) ## Get signal control before changing values ctlr = True RtlabApi.GetSystemControl(ctlr) #log.info ("=====The system control is acquired.") RtlabApi.GetSignalControl(ctlr) #log.info ("=====The signal control is acquired.") RtlabApi.Pause() #log.info ("=====The model is paused.") RtlabApi.SetSignalsByName(inputNames, inputValues) #log.info ("=====The signals are set.") timeFactor = 1 RtlabApi.Execute(timeFactor) #log.info ("=====The model is executed.") ## Release signal control after changing values ctlr = False RtlabApi.GetSignalControl(ctlr) #log.info ("=====The signal control is released.") RtlabApi.GetSystemControl(ctlr) #log.info ("=====The system control is released.") except Exception: ## Ignore error 11 which is raised when ## RtlabApi.DisplayInformation is called whereas there is no ## pending message info = sys.exc_info() if info[1][ 0] != 11: # 'There is currently no data waiting.' ## If a exception occur: stop waiting log.error ("=====setData(): An error occured at simulationTime={!s} while setting the " \ "input values for the input names={!s}.".format(simulationTime, inputNames)) raise ## if the model is not running else: ## Print the model state log.error( "=====setData(): The model state is not running. Simulation will be terminated." ) raise end = datetime.now() log.info( '==========setData(): Send values={!s} of inputs with names={!s} in {!s} seconds.' .format(inputValues, inputNames, (end - start).total_seconds())) finally: ## Always disconnect from the model when the connection RtlabApi.Disconnect() else: RtlabApi.Disconnect() log.info ("=====setData(): The simulation stoptime={!s} is reached. "\ " the connection is closed.".format(RtlabApi.GetStopTime()))
def connectToModelTest(project, model): """Takes the name of the model to connect to(string) and connects based on current model state""" # project = 'Connect1' # model = 'rtdemo1' # connect to the local project try: modelState, realTimeMode = OpalApiPy.GetModelState() except: projectPath = 'C:/RT-LABv11_Workspace_New/' projectName = os.path.join(projectPath, str(project) + '/' + str(project) + '.llp') modelPath = os.path.join(projectPath, 'Simulink/') modelName = str(model) + '.mdl' #Connects to Project RtlabApi.OpenProject(projectName) print "Now connected to '%s' project." % projectName #Connects to model #filename = os.path.join(modelPath,modelName) # OpalApiPy.SetCurrentModel(filename) modelState, realTimeMode = OpalApiPy.GetModelState() # print "Model State Connected is %s." %modelStateList[modelState] print "Now connected to %s model." % modelName #print "Model state 1 is %s" %modelStateList[modelState] # OpalApiPy.StartCompile2((("",31),)) # print"compiling" # OpalApiPy.RegisterDisplay(OpalApiPy.DISPLAY_REGISTER_ALL) # OpalApiPy.DisplayInformation(0) try: # Acquire Model State, Get system control modelState, realTimeMode = OpalApiPy.GetModelState() print "Model state is %s'." % modelStateList[modelState] # Model Connection Parameters systemControl = 0 # modelName = '' modelPath = '' exactMatch = 0 returnOnAmbiquity = 0 # Connect API to model if already running if modelState == OpalApiPy.MODEL_RUNNING: instanceId = OpalApiPy.ConnectByName(str(model)) print "Now connected to running model %s.\n" % model # print ("instanceId is: ", str(instanceId)) elif (modelState == OpalApiPy.MODEL_LOADABLE): # If model is not loaded,load and ask to execute realTimeMode = realTimeModeList['Software Sync'] timeFactor = 1 OpalApiPy.Load(realTimeMode, timeFactor) print "RT Project %s is Loading." % project OpalApiPy.LoadConsole() print "Model %s console is loading" % model chooseExecute = raw_input( "Loading Complete.Would you like to execute model now? y/n " ) chooseExecute = 'y' if chooseExecute == 'y': try: print "Now Executing Model" systemControl = 1 OpalApiPy.GetSystemControl(systemControl) print "System Control Granted" # OpalApiPy.LoadConsole() # print "Model %s console is loading" % model OpalApiPy.ExecuteConsole() print "Model %s console is executed" % model OpalApiPy.Execute(1) #sleep(10) modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] if ((modelState == OpalApiPy.MODEL_RUNNING) | (modelState == OpalApiPy.MODEL_LOADED)): print "Model Running" else: modelState, realTimeMode = OpalApiPy.GetModelState( ) print "Model State is %s" % modelStateList[ modelState] print "Model Not executed" transitionToPause() # systemControl = 1 # OpalApiPy.GetSystemControl(systemControl) # OpalApiPy.ResetConsole() # print "System Control Granted" # print "Console is now reset" # # resets the model after loading # OpalApiPy.Pause() # print "Model %s is now paused" % model # # OpalApiPy.Reset() # # print "Model %s is now reset." %model # # systemControl = 0 # OpalApiPy.GetSystemControl(systemControl) # print "System Control is released" # # OpalApiPy.Disconnect() # # print "Disconnected from %s model" % modelName except: modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] print "Model Not executed" transitionToPause() # print "Module execution unsuccessful" # systemControl = 1 # OpalApiPy.GetSystemControl(systemControl) # OpalApiPy.ResetConsole() # print "System Control Granted" # print "Console is now reset" # # resets the model after loading # OpalApiPy.Pause() # print "Model %s is now paused" % model # # OpalApiPy.Reset() # # print "Model %s is now reset." %model # # systemControl = 0 # OpalApiPy.GetSystemControl(systemControl) # print "System Control is released" # # OpalApiPy.Disconnect() # # print "Disconnected from %s model" % modelName elif chooseExecute == 'n': print "Model not executed" # OpalApiPy.ExecuteConsole() # OpalApiPy.PauseConsole() elif (modelState == OpalApiPy.MODEL_LOADED): # If model is loaded but not running, execute the model try: print "Now Executing Model" systemControl = 1 OpalApiPy.GetSystemControl(systemControl) print "System Control Granted" # Load Simulink and Matlab OpalApiPy.LoadConsole() print "Model %s console is loaded" % model OpalApiPy.ExecuteConsole() print "Model %s console is executed" % model OpalApiPy.Execute(1) modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] if ((modelState == OpalApiPy.MODEL_RUNNING) | (modelState == OpalApiPy.MODEL_LOADED)): print "Model is running" else: modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] print "Model Not executed" transitionToPause() except: modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] print "Model Not executed" fullDisconnect() elif (modelState == OpalApiPy.MODEL_PAUSED): #try: systemControl = 1 #OpalApiPy.GetSystemControl(0) #OpalApiPy.Disconnect() #OpalApiPy.ConnectByName(str(model)) OpalApiPy.GetSystemControl(systemControl) OpalApiPy.LoadConsole() print "Console loaded" OpalApiPy.ExecuteConsole() print "Model %s console is executed" % model OpalApiPy.Execute(1) print "Model %s is executed" % model modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] if ((modelState == OpalApiPy.MODEL_RUNNING) | (modelState == OpalApiPy.MODEL_LOADED)): print "Model is running" #except: # logging.error('<Model Control Released>') #fullDisconnect() else: print "Compile and Assign Model before Loading or Running" finally: print "Complete Connection Successful" # Disconnect from Model after testing # OpalApiPy.Disconnect() # print "Disconnected from %s model" %modelName #MODEL IS ALREADY CONNECTED, else: print("MODEL ALREADY CONNECTED") #OpalApiPy.Disconnect() connectToModel('IEEE39Acq', 'phasor01_IEEE39') modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] systemControl = 1 OpalApiPy.GetSystemControl(systemControl) print "System Control Granted" #systemControl = 1 # OpalApiPy.GetSystemControl(0) # OpalApiPy.Disconnect() # OpalApiPy.ConnectByName(str(model)) #OpalApiPy.GetSystemControl(systemControl) #OpalApiPy.LoadConsole() #print"Console loaded" #OpalApiPy.ExecuteConsole() #print "Model %s console is executed" % model OpalApiPy.Execute(1) print "Model %s is executed" % model modelState, realTimeMode = OpalApiPy.GetModelState() print "Model State is %s" % modelStateList[modelState] if ((modelState == OpalApiPy.MODEL_RUNNING) | (modelState == OpalApiPy.MODEL_LOADED)): print "Model is running"
if obj is not None: self.ts.log('DAS DC Measurement Device configured to be %s' % (obj.info())) self.dc_measurement_device = obj if __name__ == "__main__": import_path = "C://OPAL-RT//RT-LAB//2020.4//common//python" % rt_version try: sys.path.insert(0, import_path) import RtlabApi import OpalApiPy except ImportError as e: print( 'RtlabApi Import Error. Check the version number. Using path = %s' % import_path) print(e) system_info = RtlabApi.GetTargetNodeSystemInfo("RTServer") projectName = os.path.abspath( "C:\\Users\\DETLDAQ\\OPAL-RT\\RT-LABv2019.1_Workspace\\IEEE_1547.1_Phase_Jump\\" "models\\Phase_Jump_A_B_A\\Phase_Jump_A_B_A.llp") RtlabApi.OpenProject(projectName) print("The connection with '%s' is completed." % projectName) modelState, realTimeMode = RtlabApi.GetModelState() print(modelState, realTimeMode)