def AcquirePaused(self,signalNames=(),control_values=()): try: fd1=open('signallist.txt','a') modelState=RtlabApi.GetModelState()[0] if modelState == RtlabApi.MODEL_PAUSED: signalInfos=RtlabApi.GetSignalsDescription() for signal in signalInfos: s=str(signal)+"\n" fd1.write(s) print "Wrote signal infos to the file" else: print "Model is running!" fd1.close() except Exception as e: print "Exception:",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()
RtlabApi.Execute(1) flag=0 # Keep running the simulation and acquire the data from the OPAL target asynchronously while timecontrol<5: timecontrol=timecontrol+1 current_time=time.time() elapsed_time=(current_time-start_time) print "Time elapsed at Pause:",elapsed_time # Request time from FNCS broker to publish data from OPAL Target into FNCS print int(elapsed_time) fncs_current_time = fncs.time_request(int(elapsed_time)+1) # Read and publish all voltages #signals_l is list of all signals with different parameters signals_l=[] signalValues=() signals_l = list(RtlabApi.GetSignalsDescription()) #find only V signal values of interest for sig_name in signalNames: for item in signals_l: if sig_name in item: signalValues=signalValues+(item[6],) i=0 for voltage in voltages_topic: Voltage_real=signalValues[2*i] Voltage_imag=signalValues[2*i+1] if Voltage_imag<0: Voltage_str=str(Voltage_real) + str(Voltage_imag) + "j" else: Voltage_str=str(Voltage_real) + "+" + str(Voltage_imag) + "j" fncs.publish(voltage,Voltage_str) i+=1