Example #1
0
    def _connect(self, name_prefix=None):
        sessions = me.find_matlab()

        if not sessions:
            return

        if not name_prefix:
            name = sessions[0]
        else:
            name = ''
            for s in sessions:
                if s.startswith(name_prefix):
                    name = s
                    break
            if not name:
                return False

        try:
            self._engine = me.connect_matlab(name)
            logger.info('Connected to Matlab engine "{}"', name)
        except me.EngineError:
            logger.exception('Cannot connect to Matlab engine "{}"', name)
            return False

        self._name = name
        return True
Example #2
0
    def _connect_matlab_engine(self, use_existing=True, persistent=True):
        """
        Connect to a matlab engine, starting a new one if it hasn't been started yet

        :return:
        """

        found_eng = False
        if use_existing:
            eng_names = engine.find_matlab()
            for eng_name in eng_names:
                try:
                    self.eng = engine.connect_matlab(eng_name)
                    self.eng_name = eng_name
                    found_eng = True

                # unable to connect to an instance because it already has a connection
                except matlab.engine.EngineError:
                    pass

                if found_eng:
                    break

        if not found_eng:
            # if we're making a new persistent engine, create it
            if persistent:
                self.eng_name = self._start_persistent_shared_matlab()
                self.eng = engine.connect_matlab(self.eng_name)

            # otherwise, make a new engine just for the lifetime of self
            else:
                self.eng = engine.start_matlab()
                self.eng_name = None  # to be explicit

        self.eng_deleted = False
Example #3
0
    def _connect(self, name_prefix=None):
        sessions = me.find_matlab()

        if not sessions:
            return

        if not name_prefix:
            name = sessions[0]
        else:
            name = ''
            for s in sessions:
                if s.startswith(name_prefix):
                    name = s
                    break
            if not name:
                return False

        try:
            print('Connecting to Matlab shared engine {}'.format(name))
            self._engine = me.connect_matlab(name)
            print('Connected to Matlab shared engine {}'.format(name))
        except me.EngineError:
            return False

        self._name = name
        return True
Example #4
0
 def post(self, server):
   global matlab
   matlab = matlabEngine.connect_matlab(matlabEngine.find_matlab()[0])
   opcClient = "opcClient" + server.replace(".", "")
   opcItemGroup = "opcItemGroup" + server.replace(".", "")
   matlab.eval(opcClient + " = opcda('localhost','" + server + "')", nargout=0)
   matlab.eval("connect(" + opcClient + ")", nargout=0)
   matlab.eval(opcItemGroup + " = addgroup(" + opcClient + ")", nargout=0)
   matlab.eval("opcClientStatus = " + opcClient + ".Status", nargout=0)
   opcServers[server] = {"id": server, "client": opcClient,
                         "status": matlab.workspace["opcClientStatus"], "itemGroup": opcItemGroup, "items": []}
   return matlab.workspace["opcClientStatus"]
Example #5
0
    def _start_persistent_shared_matlab(self):
        from os import system
        from datetime import datetime

        previous_sessions_tup = engine.find_matlab()

        if self.daemon == 'screen':
            session_name = 'matlab_' + datetime.utcnow().isoformat()
            # start matlab in detached screen session and run command to share the session
            system('screen -dmS ' + session_name + ' ' +
                   self.get_matlab_bin_path() + " " + MATLAB_OPTIONS)
        else:
            raise NotImplementedError

        # wait till we see a new shared matlab sesh
        new_sessions_tup = engine.find_matlab()
        while (new_sessions_tup == previous_sessions_tup):
            time.sleep(1)
            new_sessions_tup = engine.find_matlab()

        return new_sessions_tup[-1]
Example #6
0
def new_matlab_engine(matlab_mode):
    """
    matlab_mode = 0 ,创建一个新的matlab会话。
    matlab_mode = 1 ,连接到一个已经打开的matlab共享会话(窗口)。
    连接到共享 MATLAB 会话的过程: 
    首先,从 MATLAB 调用 matlab.engine.shareEngine 将其转换为共享会话。
    若没有这句话,则megn.find_matlab() 不会找到该matlab会话。
    matlab_mode 为其他,返回None。
    """
    if matlab_mode == 0:
        return megn.start_matlab()
    elif matlab_mode == 1:
        matlab_number = megn.find_matlab()[0]
        return megn.connect_matlab(matlab_number, async=False)
    else:
        return None
Example #7
0
def runHATL(script, modelfile, modelname=None, fromMATLAB=False):

    global scriptFile
    scriptFile = script

    s = FileStream(script)
    parser = ReaffirmParser(CommonTokenStream(ReaffirmLexer(s)))
    tree = parser.prog()
    print(tree.toStringTree(recog=parser))

    sessions = engine.find_matlab()
    eng = None
    if sessions == () or fromMATLAB:
        print("Starting MATLAB engine")
        eng = engine.start_matlab()
    else:
        print("Connecting to MATLAB engine")
        eng = engine.connect_matlab(sessions[0])

    #set the appropriate path and then restore the cwd
    oldpwd = eng.pwd()
    assert ('REAFFIRM_ROOT' in os.environ)
    eng.cd(os.environ['REAFFIRM_ROOT'])
    eng.addpath(eng.genpath('functions'))
    eng.cd(oldpwd)

    print("Loading Initial Model")
    eng.clear('all', nargout=0)
    eng.bdclose('all', nargout=0)

    try:
        eng.load_system(modelfile)
    except MatlabExecutionError as e:
        print("Unable to open model '" + modelfile + "'", file=sys.stderr)
        exit()

    v = MATLABVisitor(eng, modelfile, modelname)
    v.visit(tree)
    print(v)

    return v
Example #8
0
    def __init__(self, inputargs):
        self.matlab = {}
        # declare a dictionay of equivalent functions
        self.funcMap = {'replace': 'strrep', 'addTransition': 'add_transition'}
        self.fieldMap = {'flow': 'Label', 'guardLabel': 'LabelString'}

        sessions = engine.find_matlab()
        if sessions == ():
            print("Starting MATLAB engine")
            self.eng = engine.start_matlab()
        else:
            print("Connecting to MATLAB engine")
            self.eng = engine.connect_matlab(sessions[0])

        print("loading model")
        # TODO: how do we handle/catch MatlabExecutionErrors?
        self.eng.load_system(args['modelName'])
        e = self.eng
        self.model = e.find(
            e.find(e.sfroot(), '-isa', 'Simulink.BlockDiagram'), '-isa',
            'Stateflow.Chart')
Example #9
0
 def get(self):
   matlab = matlabEngine.connect_matlab(matlabEngine.find_matlab()[0])
   return matlab.opcserverinfo('localhost', nargout=1)["ServerID"]