Example #1
0
 def __init__(self, host='localhost', port=7496, clientId=0, **options):
     self.host, self.port, self.clientId = host, port, clientId
     self.client = EClientSocket(Dispatcher(self))
     self.listeners = {}
     self.options = options
Example #2
0
class Connection(object):
    Listener = namedtuple('Listener', 'func args options')

    def __init__(self, host='localhost', port=7496, clientId=0, **options):
        self.host, self.port, self.clientId = host, port, clientId
        self.client = EClientSocket(Dispatcher(self))
        self.listeners = {}
        self.options = options

    def connect(self):
        self.client.eConnect(self.host, self.port, self.clientId)
        if not self.client.isConnected():
            raise IOError

    def close(self):
        self.client.eDisconnect()

    def listener(self, *names, **options):
        def decorator(func):
            for name in names:
                self.register(name, func, **options)
            return func
        return decorator

    def register(self, name, func, *args, **options):
        if name not in messages:
            raise KeyError(name)
        if not callable(func):
            raise TypeError(func)
        listeners = self.listeners.setdefault(name, [])
        for listener in listeners:
            if listener.func is func:
                raise ValueError(name, func)
        listeners.append(self.Listener(func, args, options))

    def unregister(self, name, func):
        if name not in messages:
            raise KeyError(name)
        if not callable(func):
            raise TypeError(func)
        listeners = self.listeners.get(name, [])
        for listener in listeners:
            if listener.func is func:
                return listeners.remove(listener)
        raise ValueError(name, func)

    def getListeners(self, name):
        if name not in messages:
            raise KeyError(name)
        return [listener.func for listener in self.listeners.get(name, [])]

    def registerAll(self, func):
        for name in messages.keys():
            try:
                self.register(name, func)
            except ValueError:
                pass

    def unregisterAll(self, func):
        for name in messages.keys():
            try:
                self.unregister(name, func)
            except ValueError:
                pass

    def enableLogging(self, enable=True):
        if enable:
            self.registerAll(self.logMessage)
        else:
            self.unregisterAll(self.logMessage)

    @staticmethod
    def logMessage(msg):
        print(msg, file=sys.stderr)

    def __getattr__(self, name):
        return getattr(self.client, name)