@@ -44,7 +44,6 @@ class which means it will use OMCSessionZMQ by default. If you want to use
4444import platform
4545import psutil
4646import re
47- import shlex
4847import signal
4948import subprocess
5049import sys
@@ -56,7 +55,8 @@ class which means it will use OMCSessionZMQ by default. If you want to use
5655import numpy as np
5756import pyparsing
5857import importlib
59-
58+ import zmq
59+ import warnings
6060
6161if sys .platform == 'darwin' :
6262 # On Mac let's assume omc is installed here and there might be a broken omniORB installed in a bad place
@@ -552,156 +552,8 @@ def getClassNames(self, className=None, recursive=False, qualified=False, sort=F
552552 str (builtin ).lower (), str (showProtected ).lower ()))
553553 return value
554554
555-
556555class OMCSession (OMCSessionHelper , OMCSessionBase ):
557556
558- def __init__ (self , readonly = False , serverFlag = '--interactive=corba' , timeout = 10.0 ,
559- docker = None , dockerContainer = None , dockerExtraArgs = None , dockerOpenModelicaPath = "omc" ,
560- dockerNetwork = None , omhome : str = None ):
561- if dockerExtraArgs is None :
562- dockerExtraArgs = []
563-
564- OMCSessionHelper .__init__ (self , omhome = omhome )
565- OMCSessionBase .__init__ (self , readonly )
566- self ._create_omc_log_file ("objid" )
567- # Locating and using the IOR
568- if sys .platform != 'win32' or docker or dockerContainer :
569- self ._port_file = "openmodelica." + self ._currentUser + ".objid." + self ._random_string
570- else :
571- self ._port_file = "openmodelica.objid." + self ._random_string
572- self ._port_file = os .path .join ("/tmp" if (docker or dockerContainer ) else self ._temp_dir , self ._port_file ).replace ("\\ " , "/" )
573- # set omc executable path and args
574- self ._docker = docker
575- self ._dockerContainer = dockerContainer
576- self ._dockerExtraArgs = dockerExtraArgs
577- self ._dockerOpenModelicaPath = dockerOpenModelicaPath
578- self ._dockerNetwork = dockerNetwork
579- self ._timeout = timeout
580- self ._create_omc_log_file ("port" )
581-
582- self ._set_omc_command ([serverFlag , "+c={0}" .format (self ._random_string )])
583-
584- # start up omc executable, which is waiting for the CORBA connection
585- self ._start_omc_process (timeout )
586- # connect to the running omc instance using CORBA
587- self ._connect_to_omc (timeout )
588-
589- def __del__ (self ):
590- OMCSessionBase .__del__ (self )
591-
592- def _connect_to_omc (self , timeout ):
593- # add OPENMODELICAHOME\lib\python to PYTHONPATH so python can load omniORB imports
594- sys .path .append (os .path .join (self .omhome , 'lib' , 'python' ))
595- # import the skeletons for the global module
596- try :
597- from omniORB import CORBA
598- from OMPythonIDL import _OMCIDL
599- except ImportError :
600- self ._omc_process .kill ()
601- raise
602- self ._omc_corba_uri = "file:///" + self ._port_file
603- # See if the omc server is running
604- attempts = 0
605- while True :
606- if self ._dockerCid :
607- try :
608- self ._ior = subprocess .check_output (["docker" , "exec" , self ._dockerCid , "cat" , self ._port_file ], stderr = subprocess .DEVNULL if (sys .version_info > (3 , 0 )) else subprocess .STDOUT ).decode ().strip ()
609- break
610- except subprocess .CalledProcessError :
611- pass
612- if os .path .isfile (self ._port_file ):
613- # Read the IOR file
614- with open (self ._port_file , 'r' ) as f_p :
615- self ._ior = f_p .readline ()
616- break
617- attempts += 1
618- if attempts == 80 :
619- name = self ._omc_log_file .name
620- self ._omc_log_file .close ()
621- with open (name ) as fin :
622- contents = fin .read ()
623- self ._omc_process .kill ()
624- raise Exception ("OMC Server is down (timeout=%f). Please start it! If the OMC version is old, try OMCSession(..., serverFlag='-d=interactiveCorba') or +d=interactiveCorba. Log-file says:\n %s" % (timeout , contents ))
625- time .sleep (timeout / 80.0 )
626-
627- while True :
628- if self ._dockerCid :
629- try :
630- self ._port = subprocess .check_output (["docker" , "exec" , self ._dockerCid , "cat" , self ._port_file ]).decode ().strip ()
631- break
632- except :
633- pass
634- else :
635- if os .path .isfile (self ._port_file ):
636- # Read the port file
637- with open (self ._port_file , 'r' ) as f_p :
638- self ._port = f_p .readline ()
639- os .remove (self ._port_file )
640- break
641-
642- attempts += 1
643- if attempts == 80.0 :
644- name = self ._omc_log_file .name
645- self ._omc_log_file .close ()
646- logger .error ("OMC Server is down (timeout=%f). Please start it! Log-file says:\n %s" % open (name ).read ())
647- raise Exception ("OMC Server is down. Could not open file %s" % (timeout ,self ._port_file ))
648- time .sleep (timeout / 80.0 )
649-
650- logger .info ("OMC Server is up and running at {0}" .format (self ._omc_corba_uri ))
651- # initialize the ORB with maximum size for the ORB set
652- sys .argv .append ("-ORBgiopMaxMsgSize" )
653- sys .argv .append ("2147483647" )
654- self ._orb = CORBA .ORB_init (sys .argv , CORBA .ORB_ID )
655-
656- # Find the root POA
657- self ._poa = self ._orb .resolve_initial_references ("RootPOA" )
658- # Convert the IOR into an object reference
659- self ._obj_reference = self ._orb .string_to_object (self ._ior )
660- # Narrow the reference to the OmcCommunication object
661- self ._omc = self ._obj_reference ._narrow (_OMCIDL .OmcCommunication )
662- # Check if we are using the right object
663- if self ._omc is None :
664- logger .error ("Object reference is not valid" )
665- raise Exception
666-
667- def execute (self , command ):
668- ## check for process is running
669- p = self ._omc_process .poll ()
670- if (p == None ):
671- result = self ._omc .sendExpression (command )
672- if command == "quit()" :
673- self ._omc = None
674- return result
675- else :
676- answer = OMParser .check_for_values (result )
677- return answer
678- else :
679- raise Exception ("Process Exited, No connection with OMC. Create a new instance of OMCSession" )
680-
681- def sendExpression (self , command , parsed = True ):
682- ## check for process is running
683- p = self ._omc_process .poll ()
684- if (p == None ):
685- result = self ._omc .sendExpression (str (command ))
686- if command == "quit()" :
687- self ._omc = None
688- return result
689- else :
690- if parsed is True :
691- answer = OMTypedParser .parseString (result )
692- return answer
693- else :
694- return result
695- else :
696- raise Exception ("Process Exited, No connection with OMC. Create a new instance of OMCSession" )
697-
698- try :
699- import zmq
700- except ImportError :
701- pass
702-
703- class OMCSessionZMQ (OMCSessionHelper , OMCSessionBase ):
704-
705557 def __init__ (self , readonly = False , timeout = 10.00 ,
706558 docker = None , dockerContainer = None , dockerExtraArgs = None , dockerOpenModelicaPath = "omc" ,
707559 dockerNetwork = None , port = None , omhome : str = None ):
@@ -770,7 +622,6 @@ def _connect_to_omc(self, timeout):
770622 logger .info ("OMC Server is up and running at {0} pid={1} cid={2}" .format (self ._omc_zeromq_uri , self ._omc_process .pid , self ._dockerCid ))
771623
772624 # Create the ZeroMQ socket and connect to OMC server
773- import zmq
774625 context = zmq .Context .instance ()
775626 self ._omc = context .socket (zmq .REQ )
776627 self ._omc .setsockopt (zmq .LINGER , 0 ) # Dismisses pending messages if closed
@@ -812,14 +663,20 @@ def sendExpression(self, command, parsed=True):
812663 else :
813664 raise Exception ("Process Exited, No connection with OMC. Create a new instance of OMCSession" )
814665
666+ class OMCSessionZMQ (OMCSession ):
667+ def __init__ (self , * args , ** kwargs ):
668+ warnings .warn (
669+ "OMCSessionZMQ is deprecated and will be remove in the next release. Please use OMCSession instead." ,
670+ DeprecationWarning ,
671+ stacklevel = 2
672+ )
673+ super (OMCSessionZMQ , self ).__init__ (* args , ** kwargs )
815674
816675class ModelicaSystemError (Exception ):
817676 pass
818677
819-
820678class ModelicaSystem (object ):
821- def __init__ (self , fileName = None , modelName = None , lmodel = None ,
822- useCorba = False , commandLineOptions = None ,
679+ def __init__ (self , fileName = None , modelName = None , lmodel = None , commandLineOptions = None ,
823680 variableFilter = None , customBuildDirectory = None , verbose = True , raiseerrors = False ,
824681 omhome : str = None ): # 1
825682 """
@@ -832,10 +689,7 @@ def __init__(self, fileName=None, modelName=None, lmodel=None,
832689 ex: myModel = ModelicaSystem("ModelicaModel.mo", "modelName")
833690 """
834691 if fileName is None and modelName is None and not lmodel : # all None
835- if useCorba :
836- self .getconn = OMCSession (omhome = omhome )
837- else :
838- self .getconn = OMCSessionZMQ (omhome = omhome )
692+ self .getconn = OMCSession (omhome = omhome )
839693 return
840694
841695 self .tree = None
@@ -857,12 +711,9 @@ def __init__(self, fileName=None, modelName=None, lmodel=None,
857711
858712 self ._verbose = verbose
859713
860- if useCorba :
861- self .getconn = OMCSession (omhome = omhome )
862- else :
863- self .getconn = OMCSessionZMQ (omhome = omhome )
714+ self .getconn = OMCSession (omhome = omhome )
864715
865- ## needed for properly deleting the OMCSessionZMQ
716+ ## needed for properly deleting the session
866717 self ._omc_log_file = self .getconn ._omc_log_file
867718 self ._omc_process = self .getconn ._omc_process
868719
@@ -1885,41 +1736,3 @@ def getLinearStates(self):
18851736 >>> getLinearStates()
18861737 """
18871738 return self .linearstates
1888-
1889-
1890- def FindBestOMCSession (* args , ** kwargs ):
1891- """
1892- Analyzes the OMC executable version string to find a suitable selection
1893- of CORBA or ZMQ, as well as older flags to launch the executable (such
1894- as +d=interactiveCorba for RML-based OMC).
1895-
1896- This is mainly useful if you are testing old OpenModelica versions using
1897- the latest OMPython.
1898- """
1899- base = OMCSessionHelper ()
1900- omc = base ._get_omc_path ()
1901- versionOK = False
1902- for cmd in ["--version" , "+version" ]:
1903- try :
1904- v = str (subprocess .check_output ([omc , cmd ], stderr = subprocess .STDOUT ))
1905- versionOK = True
1906- break
1907- except subprocess .CalledProcessError :
1908- pass
1909- if not versionOK :
1910- raise Exception ("Failed to use omc --version or omc +version. Is omc on the PATH?" )
1911- zmq = False
1912- v = v .strip ().split ("-" )[0 ].split ("~" )[0 ].strip ()
1913- a = re .search (r"v?([0-9]+)[.]([0-9]+)[.][0-9]+" , v )
1914- try :
1915- major = int (a .group (1 ))
1916- minor = int (a .group (2 ))
1917- if major > 1 or (major == 1 and minor >= 12 ):
1918- zmq = True
1919- except :
1920- pass
1921- if zmq :
1922- return OMCSessionZMQ (* args , ** kwargs )
1923- if cmd == "+version" :
1924- return OMCSession (* args , serverFlag = "+d=interactiveCorba" , ** kwargs )
1925- return OMCSession (* args , serverFlag = "-d=interactiveCorba" , ** kwargs )
0 commit comments