Kemp’s Blog

A technical blog about technical things

OpenModelica and Python via CORBA (Part 3: Python wrapper, code listing)

(omc.py)

import os
import getpass
from omniORB import CORBA

import idl._GlobalIDL as _GlobalIDL


class OMCError(Exception):
    pass


class OMCServerDownError(OMCError):
    def __init__(self, filename):
        self.filename = filename
    def __str__(self):
        return "Could not find file '%s'" % self.filename


class InvalidOMCServerRefError(OMCError):
    pass


class OMC:
    def __init__(self):
        pass
                
    def connect(self):
        orb = CORBA.ORB_init(["-ORBInitRef", "mico-local-orb=corbaloc::localhost:0/mico-local-orb"], CORBA.ORB_ID)
        omc_objid_file = "/tmp/openmodelica.%s.objid" % getpass.getuser()
        omc_corba_uri = "file:///" + omc_objid_file

        # See if the omc server is running
        if not os.path.isfile(omc_objid_file):
            raise OMCServerDownError(omc_objid_file)

        objid_file = open(omc_objid_file)
        ior = objid_file.readline()
        objid_file.close()

        mico_obj = orb.resolve_initial_references("RootPOA")

        obj = orb.string_to_object(ior)
        omc = obj._narrow(_GlobalIDL.OmcCommunication)

        if omc is None:
            raise InvalidOMCServerRefError
        
        self.omc = omc

    def _send_command(self, command):
        return self.omc.sendExpression(command)

    def get_current_directory(self):
        return self._send_command('cd()').rstrip()[1:-1]
        
    def clear(self):
        if self._send_command('clear()').rstrip() == 'true':
            return True
        return False
    
    def list_classes(self):
        return self._send_command('list()').rstrip()[1:-1].rstrip()
    
    def list_class(self, classname):
        return self._send_command('list(%s)' % classname).rstrip()[1:-1].rstrip()
        
    def list_variables(self):
        return self._send_command('listVariables()').rstrip()
    
    def load_file(self, filename):
        if self._send_command('loadFile("%s")' % filename).rstrip() == 'true':
            return True
        return False
    
    def plot(self, variable):
        if self._send_command('plot(%s)' % variable).rstrip() == 'true':
            return True
        return False
    
    def simulate(self, classname, **args):
        options = [', %s=%s' % (k, v) for k,v in args.iteritems()]
        options = ''.join(options)
        return self._send_command('simulate(%s%s)' % (classname, options)).rstrip()