MultiEndClient.py 2.22 KB
import time

from Event.EventDispatcher import EventDispatcher, CLIENT
from Event.EventHandler import EventHandler
import Event.Signal as Signal

from Communication.Manager import CommunicationManager
from Communication.EndPoint import CommunicationEndPoint
from Communication.ProtocolHandler import ProtocolHandler
from Transport.IoHandler import IoHandler

class MultiEndClient(EventHandler):
    def __init__(self):
        self._event_methods = {
            EventDispatcher.eventId('user_wait')     : self._userInteraction,
            CommunicationEndPoint.eventId('new_msg') : self._handleData
        }

        self._con_mngr = CommunicationManager()

        self._dispatcher = EventDispatcher(CLIENT)
        self._dispatcher.registerHandler(self._con_mngr)
        self._dispatcher.registerHandler(IoHandler())
        self._dispatcher.registerHandler(ProtocolHandler())
        self._dispatcher.registerHandler(self)
        Signal.initSignals(self._dispatcher)

        self._end_point   = None
        self._timeout     = None
        self._starttime   = None
        self._request     = None
        self._response    = None
        self._sendIssued  = False


    def issue(self, end_point, request, timeout):
        self._starttime   = time.time()
        self._timeout     = timeout
        self._request     = request
        self._response    = None
        self._sendIssued  = False
        self._end_point   = end_point
        self._con_mngr.addEndPoint(end_point)
        self._dispatcher.start()

        return self._response

    def _userInteraction(self, event):
        if self._sendIssued:
            now = time.time()

            if self._response or self._timeout <= (now - self._starttime):
                event.subject.stop()
            else:
                self.issueEvent(
                    event.subject,
                    'data_wait',
                    self._timeout - (now - self._starttime)
                )
        else:
            self.issueEvent(self._end_point, 'send_msg', self._request)
            self._sendIssued = True
        return True

    def _handleData(self, event):
        if event.data.isResponse():
            self._response = event.data
        return True

# vim: set ft=python et ts=8 sw=4 sts=4: