Skip to content

Commit c039c90

Browse files
committed
Removed corba support
OMCSession now uses zeromq. OMCSessionZMQ is just an alias for OMCSession. Using it will give a deprecation warning. It will be removed in the next release. Updated README.md
1 parent 5368216 commit c039c90

3 files changed

Lines changed: 21 additions & 277 deletions

File tree

OMPython/__init__.py

Lines changed: 14 additions & 201 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ class which means it will use OMCSessionZMQ by default. If you want to use
4444
import platform
4545
import psutil
4646
import re
47-
import shlex
4847
import signal
4948
import subprocess
5049
import sys
@@ -56,7 +55,8 @@ class which means it will use OMCSessionZMQ by default. If you want to use
5655
import numpy as np
5756
import pyparsing
5857
import importlib
59-
58+
import zmq
59+
import warnings
6060

6161
if 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-
556555
class 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

816675
class ModelicaSystemError(Exception):
817676
pass
818677

819-
820678
class 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)

README.md

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,29 @@
11
# OMPython
22

3-
OMPython is a Python interface that uses ZeroMQ or CORBA (omniORB) to
3+
OMPython is a Python interface that uses ZeroMQ to
44
communicate with OpenModelica.
55

66
[![FMITest](https://github.com/OpenModelica/OMPython/actions/workflows/FMITest.yml/badge.svg)](https://github.com/OpenModelica/OMPython/actions/workflows/FMITest.yml)
77
[![Test](https://github.com/OpenModelica/OMPython/actions/workflows/Test.yml/badge.svg)](https://github.com/OpenModelica/OMPython/actions/workflows/Test.yml)
88

99
## Dependencies
1010

11-
### Using ZeroMQ
12-
1311
- Python 2.7 and 3.x supported
1412
- PyZMQ is required
1513

16-
### Using omniORB
17-
18-
- Currently, only Python 2.7 is supported
19-
- omniORB is required:
20-
- Windows: included in the OpenModelica installation
21-
- Linux: Install omniORB including Python 2 support (the omniidl
22-
command needs to be on the PATH). On Ubuntu, this is done by
23-
running
24-
`sudo apt-get install omniorb python-omniorb omniidl omniidl-python`
25-
2614
## Installation
2715

2816
Installation using `pip` is recommended.
2917

30-
### Linux
31-
32-
Install the latest OMPython master by running:
18+
### Via pip
3319

3420
```bash
35-
python -m pip install -U https://github.com/OpenModelica/OMPython/archive/master.zip
36-
```
37-
38-
### Windows
39-
40-
Install the version packed with your OpenModelica installation by running:
41-
42-
```cmd
43-
cd %OPENMODELICAHOME%\share\omc\scripts\PythonInterface
44-
python -m pip install -U .
21+
pip install OMPython
4522
```
4623

47-
### Local installation
24+
### Via source
4825

49-
To Install the latest version of the OMPython master branch
50-
only, previously cloned into `<OMPythonPath>`, run:
26+
Clone the repository and run:
5127

5228
```
5329
cd <OMPythonPath>
@@ -64,8 +40,8 @@ help(OMPython)
6440
```
6541

6642
```python
67-
from OMPython import OMCSessionZMQ
68-
omc = OMCSessionZMQ()
43+
from OMPython import OMCSession
44+
omc = OMCSession()
6945
omc.sendExpression("getVersion()")
7046
```
7147

setup.py

Lines changed: 0 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,6 @@
11
from setuptools import setup
2-
from subprocess import call
3-
import os
4-
import shutil
5-
6-
def warningOrError(errorOnFailure, msg):
7-
if errorOnFailure:
8-
raise Exception(msg)
9-
else:
10-
print(msg)
11-
12-
def generateIDL():
13-
errorOnFailure = not os.path.exists(os.path.join(os.path.dirname(__file__), 'OMPythonIDL', '__init__.py'))
14-
try:
15-
path_to_omc = shutil.which("omc")
16-
omhome = os.path.dirname(os.path.dirname(os.path.split(path_to_omc)))
17-
except BaseException:
18-
omhome = None
19-
omhome = omhome or os.environ.get('OPENMODELICAHOME')
20-
21-
if omhome is None:
22-
warningOrError(errorOnFailure, "Failed to find OPENMODELICAHOME (searched for environment variable as well as the omc executable)")
23-
return
24-
idl = os.path.join(omhome, "share", "omc", "omc_communication.idl")
25-
if not os.path.exists(idl):
26-
warningOrError(errorOnFailure, "Path not found: %s" % idl)
27-
return
28-
29-
if 0 != call(["omniidl", "-bpython", "-Wbglobal=_OMCIDL", "-Wbpackage=OMPythonIDL", idl]):
30-
warningOrError(errorOnFailure, "omniidl command failed")
31-
return
32-
print("Generated OMPythonIDL files")
33-
34-
35-
try:
36-
# if we don't have omniidl or omniORB then don't try to generate OMPythonIDL files.
37-
try:
38-
import omniidl
39-
except ImportError:
40-
import omniORB
41-
hasomniidl = True
42-
generateIDL()
43-
except ImportError:
44-
hasomniidl = False
452

463
OMPython_packages = ['OMPython', 'OMPython.OMParser']
47-
if hasomniidl:
48-
OMPython_packages.extend(['OMPythonIDL', 'OMPythonIDL._OMCIDL', 'OMPythonIDL._OMCIDL__POA'])
494

505
setup(name='OMPython',
516
version='3.6.0',

0 commit comments

Comments
 (0)