コード例 #1
0
 def Acquire(self,acqGroup=1, synchronization = 0,interpolation = 0,threshold = 0,acqTimeStep = 0.1,frameSize = 0):
     
     try:
         # File where the acquisition results are dumped       
         fd=open('output.txt','a')
         stp=1
         #Check if the model is running
         modelState= RtlabApi.GetModelState()[0]
         if (modelState == RtlabApi.MODEL_RUNNING):
             #Reading all values in the acquisition buffer            
             frameSize=0
             while 1:
                 # Get the data for an entire acquisition buffer
                 acqResults = RtlabApi.GetAcqGroupSyncSignals(acqGroup-1, synchronization,interpolation,threshold, acqTimeStep)
                 simSignals,monSignals,simTimeStep,endFrame = acqResults
                 missedData,offset,simTime,sampleSec = monSignals
                 frameSize+=1
                 # Print the last time stamp value in the buffer
                 if endFrame:
                     str="T%d: Last Time Stamp Value in Buffer for Acquisition Group #%d : %f\n" %(acqGroup,acqGroup, simTimeStep)
                     fd.write(str)
                     #print "T%d: Last Time Stamp Value in Buffer for Acquisition Group #%d : %f\n" %(acqGroup,acqGroup, simTimeStep)
                     break
             else :
                 print "Model is in:",modelState
                 
         # Close the file
         fd.close()
     except Exception as e:
         print "Exception:",str(e)
コード例 #2
0
 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)
コード例 #3
0
 def Snapshot(self,option=0,filename = 'snapshotfile',overwrite = 1,increment = 0,comment = '',commentLen = 0):
     try:
         # First we need to connect to the model
         modelState=RtlabApi.GetModelState()[0]
         
         # We take or retrieve snapshot only when the model is in the paused state
         if modelState == RtlabApi.MODEL_RUNNING:
             
             print "Model is running! Please ensure that the model is paused before calling Snapshot."
         
         elif modelState == RtlabApi.MODEL_PAUSED:
             
             # Get control of the model before you take/retrieve Snapshots
             monitoringControl = 1
             OpalApiPy.GetMonitoringControl(monitoringControl)
             OpalApiPy.Snapshot(option, filename, overwrite, increment, comment, commentLen)
             # Relinquish control
             monitoringControl = 0
             OpalApiPy.GetMonitoringControl(monitoringControl)
             ## 1 = take snapshot, 2 = restore snapshot
             if option ==1:
                 print "Saved a snapshot successfully."
             elif option ==2:
                 print "Retrieved a snapshot successfuly."
             else:
                 print "Invalid Snapshot option. 1 - Take Snapshot, 2 - Retrieve Snapshot"
     except Exception as e:
         monitoringControl = 0
         OpalApiPy.GetMonitoringControl(monitoringControl)
         print "Error in Taking/Retrieving Snapshot:", str(e)
コード例 #4
0
def handler(signal_received, frame):
 RtlabApi.CloseProject()
 with open('data.csv',mode='w') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_ALL)
    csv_writer.writerow(["bus1SharedCurrent","bus1Voltage","bus2SharedCurrent","bus2Voltage","current Time","bus1Time","bus2Time","Full Update Time"])
    for line in Data:
        print(line)
    for line in Data:
        csv_writer.writerow(line)
    sys.exit(0)
コード例 #5
0
 def AcquireToFile(self,enabled, acqGroup, filename="data1", variable="test"):
     try:
         # Get Acquistion control before this can be enabled
         RtlabApi.GetAcquisitionControl(1,acqGroup-1)
         # Enable/Disable the function
         OpalApiPy.SetAcqWriteFile(acqGroup-1, filename, variable, enabled)
         if enabled==0:
             print "Write to file has been disabled."
         else:
             print "Write to file has been disabled."
     except:
         print "Error in setting acquire to file option."
コード例 #6
0
    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
コード例 #7
0
 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)
コード例 #8
0
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
コード例 #9
0
ファイル: acquire.py プロジェクト: nlebang/OpalApiControl
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
コード例 #10
0
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()))
コード例 #11
0
ファイル: acquire.py プロジェクト: nlebang/OpalApiControl
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"
コード例 #12
0
        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)
コード例 #13
0
    async def updateValues():
        async with websockets.connect(uri) as websocket:
            busData = {"instr":"Opal", "BusNumber": BusNumber, "BusValue":
RtlabApi.GetSignalsByName(SignalToSend),
"currentValue":RtlabApi.GetSignalsByName(CurrentSignalToSend),
"time":str(time.time())}
コード例 #14
0
lastSendTime = time.time()
Data = []

def handler(signal_received, frame):
 RtlabApi.CloseProject()
 with open('data.csv',mode='w') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_ALL)
    csv_writer.writerow(["bus1SharedCurrent","bus1Voltage","bus2SharedCurrent","bus2Voltage","current Time","bus1Time","bus2Time","Full Update Time"])
    for line in Data:
        print(line)
    for line in Data:
        csv_writer.writerow(line)
    sys.exit(0)

signal(SIGINT,handler)
RtlabApi.OpenProject(projectName)

realTimeMode = RtlabApi.SOFT_SIM_MODE
RtlabApi.Load(realTimeMode,1)
print("The Model is Loaded")

RtlabApi.Execute(1)
print("The model is running")

# Get control
print('get control')
RtlabApi.GetSystemControl(1)
RtlabApi.GetAcquisitionControl(1)
RtlabApi.GetParameterControl(1)
RtlabApi.GetSignalControl(1)
print('got control')
コード例 #15
0
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)
コード例 #16
0
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()
コード例 #17
0
 bus_725_phB_Q
     topic = bus_7XX_phX/bus_725_phB_Q
     list=false
 bus_727_phC_Q
     topic = bus_7XX_phX/bus_727_phC_Q
     list=false"""
     
     voltages_topic = ["bus_701_phA_V","bus_701_phB_V","bus_701_phC_V","bus_712_phC_V","bus_713_phC_V","bus_714_phA_V","bus_714_phB_V","bus_718_phA_V","bus_720_phC_V","bus_722_phB_V","bus_722_phC_V","bus_724_phB_V","bus_725_phB_V","bus_727_phC_V"]
     load_p_topic = ["bus_701_phA_P","bus_701_phB_P","bus_701_phC_P","bus_712_phC_P","bus_713_phC_P","bus_714_phA_P","bus_714_phB_P","bus_718_phA_P","bus_720_phC_P","bus_722_phB_P","bus_722_phC_P","bus_724_phB_P","bus_725_phB_P","bus_727_phC_P"]
     load_q_topic = ["bus_701_phA_Q","bus_701_phB_Q","bus_701_phC_Q","bus_712_phC_Q","bus_713_phC_Q","bus_714_phA_Q","bus_714_phB_Q","bus_718_phA_Q","bus_720_phC_Q","bus_722_phB_Q","bus_722_phC_Q","bus_724_phB_Q","bus_725_phB_Q","bus_727_phC_Q"]
     parameterNames_P=('ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load1/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load2/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L712/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L713/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load1/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L718/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L720/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load1/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L724/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L725/Single-Phase Static Load13/GLD_pNom/Value','ssn_IEEE_37bus/sm_computation/L727/Single-Phase Static Load13/GLD_pNom/Value')
     parameterNames_Q=('ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load1/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load2/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L712/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L713/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load1/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L718/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L720/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load1/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L724/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L725/Single-Phase Static Load13/GLD_qNom/Value','ssn_IEEE_37bus/sm_computation/L727/Single-Phase Static Load13/GLD_qNom/Value')
     signalNames=('ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load1/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load1/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load2/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L701/Single-Phase Static Load2/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L712/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L712/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L713/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L713/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load1/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L714/Single-Phase Static Load1/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L718/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L718/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L720/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L720/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load1/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L722/Single-Phase Static Load1/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L724/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L724/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L725/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L725/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)','ssn_IEEE_37bus/sm_computation/L727/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(1)','ssn_IEEE_37bus/sm_computation/L727/Single-Phase Static Load13/Magnitude-Angle to Complex/port1(2)')
     #Initializing FNCS
     fncs.initialize(config)
     print "FNCS initialized.....\n" + str(RtlabApi.GetModelState()[0])
     # This the logic that controls the execution, acquisition and controls
     realTimeMode=realTimeModeList['Hardware Synchronized']
     timeFactor=1.0
     PauseTime=1.0
     multiplier=1
     if realTimeMode==1:
         PauseTime= PauseTime*multiplier
     # We are going to pause and resume for five different steps and at each time we need to acquire, and send control back to the model.
     loop = 0
     RtlabApi.GetSystemControl()
     RtlabApi.SetPauseTime(PauseTime-0.00)
     RtlabApi.SetStopTime(25*PauseTime-0.00)
     (modelState, realTimeMode) = RtlabApi.GetModelState()
     if modelState == RtlabApi.MODEL_PAUSED:
         start_time=time.time()