33Definition of an OMC session.
44"""
55
6+ from __future__ import annotations
7+
68__license__ = """
79 This file is part of OpenModelica.
810
3335"""
3436
3537import shutil
36- import abc
3738import getpass
3839import logging
3940import 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 :
0 commit comments