Skip to content

Commit 215875a

Browse files
committed
Merge branch 'define_OMCSessionCmd' into merge
2 parents bcfeb3c + 1ae078c commit 215875a

4 files changed

Lines changed: 63 additions & 45 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
from dataclasses import dataclass
4747
from typing import Optional
4848

49-
from OMPython.OMCSession import OMCSessionBase, OMCSessionZMQ
49+
from OMPython.OMCSession import OMCSessionZMQ
5050

5151
# define logger using the current module name as ID
5252
logger = logging.getLogger(__name__)

OMPython/OMCSession.py

Lines changed: 36 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
Definition of an OMC session.
44
"""
55

6+
from __future__ import annotations
7+
68
__license__ = """
79
This file is part of OpenModelica.
810
@@ -33,7 +35,6 @@
3335
"""
3436

3537
import shutil
36-
import abc
3738
import getpass
3839
import logging
3940
import json
@@ -80,32 +81,17 @@ class OMCSessionException(Exception):
8081
pass
8182

8283

83-
class OMCSessionBase(metaclass=abc.ABCMeta):
84+
class OMCSessionCmd:
8485

85-
def __init__(self, readonly=False):
86+
def __init__(self, session: OMCSessionZMQ, readonly: Optional[bool] = False):
87+
if not isinstance(session, OMCSessionZMQ):
88+
raise OMCSessionException("Invalid session definition!")
89+
self._session = session
8690
self._readonly = readonly
8791
self._omc_cache = {}
8892

89-
def execute(self, command):
90-
warnings.warn("This function is depreciated and will be removed in future versions; "
91-
"please use sendExpression() instead", DeprecationWarning, stacklevel=1)
92-
93-
return self.sendExpression(command, parsed=False)
94-
95-
@abc.abstractmethod
9693
def sendExpression(self, command, parsed=True):
97-
"""
98-
Sends an expression to the OpenModelica. The return type is parsed as if the
99-
expression was part of the typed OpenModelica API (see ModelicaBuiltin.mo).
100-
* Integer and Real are returned as Python numbers
101-
* Strings, enumerations, and typenames are returned as Python strings
102-
* Arrays, tuples, and MetaModelica lists are returned as tuples
103-
* Records are returned as dicts (the name of the record is lost)
104-
* Booleans are returned as True or False
105-
* NONE() is returned as None
106-
* SOME(value) is returned as value
107-
"""
108-
pass
94+
return self._session.sendExpression(command=command, parsed=parsed)
10995

11096
def _ask(self, question: str, opt: Optional[list[str]] = None, parsed: Optional[bool] = True):
11197

@@ -114,7 +100,7 @@ def _ask(self, question: str, opt: Optional[list[str]] = None, parsed: Optional[
114100
elif isinstance(opt, list):
115101
expression = f"{question}({','.join(opt)})"
116102
else:
117-
raise Exception(f"Invalid definition of options for {repr(question)}: {repr(opt)}")
103+
raise OMCSessionException(f"Invalid definition of options for {repr(question)}: {repr(opt)}")
118104

119105
p = (expression, parsed)
120106

@@ -126,10 +112,9 @@ def _ask(self, question: str, opt: Optional[list[str]] = None, parsed: Optional[
126112
logger.debug('OMC ask: %s (parsed=%s)', expression, parsed)
127113

128114
try:
129-
res = self.sendExpression(expression, parsed=parsed)
130-
except OMCSessionException:
131-
logger.error("OMC failed: %s, %s, parsed=%s", question, opt, parsed)
132-
raise
115+
res = self._session.sendExpression(expression, parsed=parsed)
116+
except OMCSessionException as ex:
117+
raise OMCSessionException("OMC _ask() failed: %s (parsed=%s)", expression, parsed) from ex
133118

134119
# save response
135120
self._omc_cache[p] = res
@@ -201,9 +186,11 @@ def getClassComment(self, className):
201186
try:
202187
return self._ask(question='getClassComment', opt=[className])
203188
except pyparsing.ParseException as ex:
204-
logger.warning("Method 'getClassComment' failed for %s", className)
205-
logger.warning('OMTypedParser error: %s', ex.msg)
189+
logger.warning("Method 'getClassComment(%s)' failed; OMTypedParser error: %s",
190+
className, ex.msg)
206191
return 'No description available'
192+
except OMCSessionException:
193+
raise
207194

208195
def getNthComponent(self, className, comp_id):
209196
""" returns with (type, name, description) """
@@ -232,13 +219,18 @@ def getParameterNames(self, className):
232219
logger.warning('OMPython error: %s', ex)
233220
# FIXME: OMC returns with a different structure for empty parameter set
234221
return []
222+
except OMCSessionException:
223+
raise
235224

236225
def getParameterValue(self, className, parameterName):
237226
try:
238227
return self._ask(question='getParameterValue', opt=[className, parameterName])
239228
except pyparsing.ParseException as ex:
240-
logger.warning('OMTypedParser error: %s', ex.msg)
229+
logger.warning("Method 'getParameterValue(%s, %s)' failed; OMTypedParser error: %s",
230+
className, parameterName, ex.msg)
241231
return ""
232+
except OMCSessionException:
233+
raise
242234

243235
def getComponentModifierNames(self, className, componentName):
244236
return self._ask(question='getComponentModifierNames', opt=[className, componentName])
@@ -273,26 +265,22 @@ def getNthComponentModification(self, className, comp_id):
273265
# end getClassNames;
274266
def getClassNames(self, className=None, recursive=False, qualified=False, sort=False, builtin=False,
275267
showProtected=False):
276-
value = self._ask(question='getClassNames',
277-
opt=[className] if className else [] + [f'recursive={str(recursive).lower()}',
278-
f'qualified={str(qualified).lower()}',
279-
f'sort={str(sort).lower()}',
280-
f'builtin={str(builtin).lower()}',
281-
f'showProtected={str(showProtected).lower()}']
282-
)
283-
return value
268+
opt = [className] if className else [] + [f'recursive={str(recursive).lower()}',
269+
f'qualified={str(qualified).lower()}',
270+
f'sort={str(sort).lower()}',
271+
f'builtin={str(builtin).lower()}',
272+
f'showProtected={str(showProtected).lower()}']
273+
return self._ask(question='getClassNames', opt=opt)
284274

285275

286-
class OMCSessionZMQ(OMCSessionBase):
276+
class OMCSessionZMQ:
287277

288-
def __init__(self, readonly=False, timeout=10.00,
278+
def __init__(self, timeout=10.00,
289279
docker=None, dockerContainer=None, dockerExtraArgs=None, dockerOpenModelicaPath="omc",
290280
dockerNetwork=None, port=None, omhome: str = None):
291281
if dockerExtraArgs is None:
292282
dockerExtraArgs = []
293283

294-
super().__init__(readonly=readonly)
295-
296284
self.omhome = self._get_omhome(omhome=omhome)
297285

298286
self._omc_process = None
@@ -530,6 +518,12 @@ def _connect_to_omc(self, timeout):
530518
self._omc.setsockopt(zmq.IMMEDIATE, True) # Queue messages only to completed connections
531519
self._omc.connect(self._port)
532520

521+
def execute(self, command):
522+
warnings.warn("This function is depreciated and will be removed in future versions; "
523+
"please use sendExpression() instead", DeprecationWarning, stacklevel=1)
524+
525+
return self.sendExpression(command, parsed=False)
526+
533527
def sendExpression(self, command, parsed=True):
534528
p = self._omc_process.poll() # check if process is running
535529
if p is not None:

OMPython/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
CONDITIONS OF OSMC-PL.
3737
"""
3838

39-
from OMPython.OMCSession import OMCSessionBase, OMCSessionZMQ, OMCSessionException
39+
from OMPython.OMCSession import OMCSessionCmd, OMCSessionZMQ, OMCSessionException
4040
from OMPython.ModelicaSystem import ModelicaSystem, ModelicaSystemError, LinearizationResult
4141

4242
# global names imported if import 'from OMPython import *' is used
@@ -47,5 +47,5 @@
4747

4848
'OMCSessionException',
4949
'OMCSessionZMQ',
50-
'OMCSessionBase',
50+
'OMCSessionCmd',
5151
]

tests/test_OMSessionCmd.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import OMPython
2+
import unittest
3+
4+
5+
class OMCSessionCmdTester(unittest.TestCase):
6+
def __init__(self, *args, **kwargs):
7+
super(OMCSessionCmdTester, self).__init__(*args, **kwargs)
8+
9+
def test_isPackage(self):
10+
omczmq = OMPython.OMCSessionZMQ()
11+
omccmd = OMPython.OMCSessionCmd(session=omczmq)
12+
assert not omccmd.isPackage('Modelica')
13+
14+
def test_isPackage2(self):
15+
mod = OMPython.ModelicaSystem(modelName="Modelica.Electrical.Analog.Examples.CauerLowPassAnalog",
16+
lmodel=["Modelica"])
17+
omccmd = OMPython.OMCSessionCmd(session=mod.getconn)
18+
assert omccmd.isPackage('Modelica')
19+
20+
# TODO: add more checks ...
21+
22+
23+
if __name__ == '__main__':
24+
unittest.main()

0 commit comments

Comments
 (0)