コード例 #1
0
ファイル: cpinet.py プロジェクト: CPHT/echobaseppp
 def __init__(self, inetResponseCallbackFunc=None, *args):
     self._target = self.inet_handler
     self._args = args
     self.__lock = threading.Lock()
     self.closing = False # A flag to indicate thread shutdown
     self.commands = Queue.Queue(32)
     #self.data_buffer = Queue.Queue(128)
     self.inet_timeout = 0
     self.inetResponseCallbackFunc = inetResponseCallbackFunc
     self.inetBusy = False
     self.inetResult = CpInetResult()
     self.inetToken = ""
     self.host = CpInetDefs.INET_HOST
     self.port = CpInetDefs.INET_PORT
     self.route = CpInetDefs.INET_ROUTE
     self.sock = None
     self.remoteIp = None
     self.initialized = False
     self.state = CpInetState.CLOSED
     self.state_timeout = time.time()
     self.exponential_backoff = 30
     self.log = CpLog()
     self.state_cb = None
     #self.data_buffer = ""
     threading.Thread.__init__(self)
コード例 #2
0
ファイル: cdksim.py プロジェクト: erudisill/cdksim
    def __init__(self, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False  # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32)
        #self.data_buffer = Queue.Queue(128)
        self.inet_timeout = 0
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.inetBusy = False
        self.inetResult = CpInetResult()
        self.inetToken = ""
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.route = CpInetDefs.INET_ROUTE
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.current_state = CpInetState.INITIALIZE
        self.inetError = CpInetError()
        self.state_timeout = time.time()
        self.exponential_backoff = 30
        self.log = CpLog()
        self.state_cb = None
        self.retries = 1
        self.waitRetryBackoff = {1: 5, 2: 15, 3: 30}
        #self.waitRetryBackoff = {1:1, 2:2, 3:3} # Test timeouts to speed up testing
        self.stateMaxRetries = 3
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time

        self.fmap = {
            0: self.init_socket,
            1: self.inet_idle,
            2: self.inet_connect,
            3: self.inet_close,
            4: self.inet_sleep,
            5: self.inet_send,
            6: self.inet_waitnetworkinterface
        }

        threading.Thread.__init__(self)
コード例 #3
0
    def __init__(self, printerThread, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False  # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32)  # Commands for this script to handle
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.inet_error = CpInetError()
        self.log = CpLog()

        self.printerID = printerThread.printerID

        self.states = CpPrinterStates(self)
        self.current_state = self.states.INITIALIZE

        # Gradually increasing backoff as more errors occur
        self.waitRetryBackoff = [5, 15, 30, 60]
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time
        self.printer_command_buffer = ""  #stores incomplete printer commands

        #An ack isn't expected until a heartbeat is sent
        self.heartbeat_ack_pending = False
        self.last_heartbeat_time = time.time()

        #Contains pending acks for print commands
        self.ack_queue = Queue.Queue(128)

        self.printerThread = printerThread

        threading.Thread.__init__(self)
コード例 #4
0
ファイル: cpinet_v2.py プロジェクト: CPHT/echobaseppp
 def __init__(self, inetResponseCallbackFunc=None, *args):
     self._target = self.inet_handler
     self._args = args
     self.__lock = threading.Lock()
     self.closing = False # A flag to indicate thread shutdown
     self.commands = Queue.Queue(32)
     #self.data_buffer = Queue.Queue(128)
     self.inet_timeout = 0
     self.inetResponseCallbackFunc = inetResponseCallbackFunc
     self.inetBusy = False
     self.inetResult = CpInetResult()
     self.inetToken = ""
     self.host = CpInetDefs.INET_HOST
     self.port = CpInetDefs.INET_PORT
     self.route = CpInetDefs.INET_ROUTE
     self.sock = None
     self.remoteIp = None
     self.initialized = False
     self.current_state = CpInetState.INITIALIZE
     self.inetError = CpInetError()
     self.state_timeout = time.time()
     self.exponential_backoff = 30
     self.log = CpLog()
     self.state_cb = None
     self.retries = 1
     self.waitRetryBackoff = {1:5, 2:15, 3:30}
     #self.waitRetryBackoff = {1:1, 2:2, 3:3} # Test timeouts to speed up testing
     self.stateMaxRetries = 3
     self.inet_stats = CpInetStats()
     self.inet_stats.LastSent = time
     
     self.fmap = {0:self.init_socket,
                  1:self.inet_idle, 
                  2:self.inet_connect, 
                  3:self.inet_close, 
                  4:self.inet_sleep,
                  5:self.inet_send,
                  6:self.inet_waitnetworkinterface}
     
     
     threading.Thread.__init__(self)
コード例 #5
0
    def __init__(self, printerThread, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32) # Commands for this script to handle
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.inet_error = CpInetError()
        self.log = CpLog()

        self.printerID = printerThread.printerID

        self.states = CpPrinterStates(self)
        self.current_state = self.states.INITIALIZE

        # Gradually increasing backoff as more errors occur
        self.waitRetryBackoff = [5, 15, 30, 60]
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time
        self.printer_command_buffer = "" #stores incomplete printer commands

        #An ack isn't expected until a heartbeat is sent
        self.heartbeat_ack_pending = False
        self.last_heartbeat_time = time.time()

        #Contains pending acks for print commands
        self.ack_queue = Queue.Queue(128)

        self.printerThread = printerThread

        threading.Thread.__init__(self)
コード例 #6
0
ファイル: cpinet_v2.py プロジェクト: CPHT/echobaseppp
class CpInet(threading.Thread):
    
    def __init__(self, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32)
        #self.data_buffer = Queue.Queue(128)
        self.inet_timeout = 0
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.inetBusy = False
        self.inetResult = CpInetResult()
        self.inetToken = ""
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.route = CpInetDefs.INET_ROUTE
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.current_state = CpInetState.INITIALIZE
        self.inetError = CpInetError()
        self.state_timeout = time.time()
        self.exponential_backoff = 30
        self.log = CpLog()
        self.state_cb = None
        self.retries = 1
        self.waitRetryBackoff = {1:5, 2:15, 3:30}
        #self.waitRetryBackoff = {1:1, 2:2, 3:3} # Test timeouts to speed up testing
        self.stateMaxRetries = 3
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time
        
        self.fmap = {0:self.init_socket,
                     1:self.inet_idle, 
                     2:self.inet_connect, 
                     3:self.inet_close, 
                     4:self.inet_sleep,
                     5:self.inet_send,
                     6:self.inet_waitnetworkinterface}
        
        
        threading.Thread.__init__(self)
    
    def get_queue_depth(self):
        return self.commands.qsize()
    
    def get_current_state(self):
        return self.lookupStateName(self.current_state)
    
    def get_inet_stats(self):
        return self.inet_stats
       
    def setStateChangedCallback(self, callback):
        self.state_cb = callback   
                        
    def lookupStateName(self, index):
        if(index == 0):
            return "INITIALIZE"
        elif(index == 1):
            return "IDLE"
        elif(index == 2):
            return "CONNECT"
        elif(index == 3):
            return "CLOSE"
        elif(index == 4):
            return "SLEEP"  
        elif(index == 5):
            return "SEND"
        elif(index == 6):
            return "WAITNETWORKINTERFACE" 
               

    def enter_state(self, new_state, timeout):
        self.current_state = new_state
        self.STATEFUNC = self.fmap[self.current_state]
        self.timestamp = datetime.now()
        self.timeout = timeout
        
        #if(CpDefs.LogVerboseInet):
        print 'enter_state: (', self.lookupStateName(self.current_state), ')'
            
        # Set the led pattern via state_cb
        # Hack if statement to prevent state_cb from being called before
        # setStateChangedCallback is set by cptaskmanager
        if (self.state_cb == None):
            return
        else:
            self.state_cb(new_state)
        
    def exit_state(self):
        self.current_state = 0
        self.STATEFUNC = 0
        self.timeout = 0.0   
        
    def state_timedout(self):
        if((datetime.now() - self.timestamp).seconds >= self.timeout):
            
            if(CpDefs.LogVerboseInet):
                print 'state_timeout: (', self.lookupStateName(self.current_state), ')'
                
            return True
        else:
            return False
        
    def reset_state_timeout(self):
        self.timestamp = datetime.now()
        
    def inet_handler(self):
        
        if (CpDefs.WatchdogWaitNetworkInterface):
            # Start out waiting for network interface
            self.enter_state(CpInetState.WAITNETWORKINTERFACE, CpInetTimeout.WAITNETWORKINTERFACE)
        else:
            # Start out initializing (Use Case for testing without watchdog)
            self.enter_state(CpInetState.INITIALIZE, CpInetTimeout.INITIALIZE)
            
        while not self.closing:
            if(self.STATEFUNC != 0):
                self.STATEFUNC()
            time.sleep(.0001)
            
        
    def run(self):
        self._target(*self._args)
        
    def shutdown_thread(self):
        print 'shutting down CpInet...'
        self.inet_close() # New code added
        self.__lock.acquire()
        self.closing = True
        self.__lock.release()
    

    def init_socket(self):
        try:
            self.remoteIp = socket.gethostbyname(self.host)
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            
            if(CpDefs.LogVerboseInet):
                print 'init_socket: successful (%s)' %self.remoteIp
                
            self.enter_state(CpInetState.CONNECT, CpInetTimeout.CONNECT)
            return True
        except socket.gaierror:
            self.log.logError('init_socket: failed (hostname could not be resolved)')
            print 'init_socket: failed (hostname could not be resolved)'
        except:      
            self.log.logError('init_socket: failed (other)')
            print 'init_socket: failed (other)'
        
        # If we get this far we received an error
        self.handle_init_socket_error()
        
        return False
    
    def handle_init_socket_error(self): 
        
        # ******** BEGIN ERROR HANDLING ********
        
        # If we get this far we received an error
        self.inetError.InitializeErrors += 1
        # Updated Statistics
        self.inet_stats.InitErrors += 1
        
        if (self.inetError.InitializeErrors > self.inetError.InitializeMax):
            print 'Max Initialize Errors'
            # Reset Error Counter
            self.inetError.InitializeErrors = 0
            # Handle Max Errors
            # TODO: TEST BEFORE PROD
            
            # Check to see if we need to update watchdog
            # if not we are in test mode and just want to remain in
            # init_socket indefinately
            if (CpDefs.WatchdogWaitNetworkInterface):
                self.watchdog_set_status(CpWatchdogStatus.Error)
                self.enter_state(CpInetState.WAITNETWORKINTERFACE, CpInetTimeout.WAITNETWORKINTERFACE)
                
            return False 
        
        # Allow some settle time before trying again
        print 'Wait Retry Backoff %d sec.' % self.waitRetryBackoff[self.inetError.InitializeErrors]
        time.sleep(self.waitRetryBackoff[self.inetError.InitializeErrors])
        
        # ******** END ERROR HANDLING ********
                      
    def inet_connect(self):
           
        try:
            self.sock.connect((self.remoteIp, self.port))
            # New Code for Timeout
            self.sock.settimeout(CpInetDefs.INET_TIMEOUT)
            # End New Code for Timeout
            
            if(CpDefs.LogVerboseInet):
                print 'inet_connect: successful'
                
            self.enter_state(CpInetState.IDLE, CpInetTimeout.IDLE)
            self.watchdog_set_status(CpWatchdogStatus.Success)
            return True
        except:         
            self.log.logError('inet_connect: failed')
            print 'inet_connect: failed'
        
        # If we get this far we received an error
        self.handle_inet_connect_error()
        
        return False


    def handle_inet_connect_error(self): 
        
        # ******** BEGIN ERROR HANDLING ********
        
        self.inetError.ConnectErrors += 1
        
        # Updated Statistics
        self.inet_stats.ConnectErrros += 1
        
        print 'CONNECT FAILED'
        
        if (self.inetError.ConnectErrors > self.inetError.ConnectMax):
            # Handle Max Errors
            self.inetError.ConnectErrors = 0
            self.enter_state(CpInetState.INITIALIZE, CpInetTimeout.INITIALIZE)
            return False 
          
        # Allow some settle time before trying again
        print 'Wait Retry Backoff %d sec.' % self.waitRetryBackoff[self.inetError.ConnectErrors]
        time.sleep(self.waitRetryBackoff[self.inetError.ConnectErrors])
        
        # ******** END ERROR HANDLING ********        
        
    def inet_send(self):
        
        # Allow the connected state to wait at least 30s before
        # going to idle. This will keep us from bouncing between
        # idle and connected states thus decreasing latency.
        # Reset the timer for each new message
        if(self.state_timedout() == True):
            self.enter_state(CpInetState.IDLE, CpInetTimeout.IDLE)
            return True

        if (self.commands.qsize() > 0):
            self.reset_state_timeout()
            
            if(CpDefs.LogVerboseInet):
                print 'Command found'
                
            packet = self.commands.get(True)
            
            
            #if(self.inet_send_packet(packet) == True):
            result = self.inet_send_packet(packet)
            
            if(result.ResultCode == CpInetResultCode.RESULT_OK):
                
                # Updated Statistics
                self.inet_stats.Sent += 1
                self.inet_stats.LastSent = time
        
                if(CpDefs.LogVerboseInet):
                    print 'SEND SUCCESSFUL'
                    
                self.commands.task_done()
            else:
                print 'inet_send error: %s' % result.Data
                self.enqueue_packet(packet)
                self.handle_inet_send_error()
                #print 'tasks in queue %d' % self.commands.qsize()
                #print 'error: ResultCode=(%d) Data=%s ' % (result.ResultCode, result.Data)
                
            return True
        else:
            # Otherwise we have no new messages and the current
            # state has not yet timed out so return True in order
            # to avoid the error handling
            return True
        
        
    def handle_inet_send_error(self): 
        
        # ******** BEGIN ERROR HANDLING ********
        
        self.inetError.SendErrors += 1
        
        # Updated Statistics
        self.inet_stats.SendErrors += 1
        
        print 'SEND FAILED'
        
        if (self.inetError.SendErrors > self.inetError.SendMax):
            # We have exceeded the maximum allowable attempts so
            # close and reinitialize the connection
            self.inetError.SendErrors = 0
            self.inet_close()
            self.enter_state(CpInetState.INITIALIZE, CpInetTimeout.INITIALIZE)
            return False 
          
        # Allow some settle time before trying again
        print 'Wait Retry Backoff %d sec.' % self.waitRetryBackoff[self.inetError.SendErrors]
        time.sleep(self.waitRetryBackoff[self.inetError.SendErrors])
        
        # ******** END ERROR HANDLING ********
            
    # inet_send_packet is explicitly called by inet_send 
    def inet_send_packet(self, packet):
        
        # Setup the HTTP request
        postData = CpInetDefs.INET_HTTPPOST % (CpInetDefs.INET_ROUTE, CpInetDefs.INET_HOST, len(packet), packet)
        
        result = CpInetResultCode()
        
        if(CpDefs.LogVerboseInet):
            print 'inet_send: (',self.remoteIp, ':', self.port, ')'
            print 'inet_send: ', postData
          
        # Send the HTTP request
        try:
            byteCount = self.sock.send(postData)
        except socket.error, e:
            result.ResultCode = CpInetResultCode.RESULT_SCKSENDERROR
            result.Data = e.args[0]
            self.log.logError('inet_send: failed')
            print 'inet_send: failed'
            return result
         
        # Process the response
        try:
            reply = self.sock.recv(4096)
        except socket.error, e:
            err = e.args[0]
            if err == 'timed out':
                result.ResultCode = CpInetResultCode.RESULT_SCKTIMEOUT
                print 'socket timeout exception'
            else:
                result.ResultCode = CpInetResultCode.RESULT_SCKRECVERROR   
                
            result.Data = e.args[0]    
                
            self.log.logError('inet_send: failed')
            print 'inet_send: failed'
            return result
コード例 #7
0
class CpPrinterService(threading.Thread):
    def __init__(self, printerThread, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False  # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32)  # Commands for this script to handle
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.inet_error = CpInetError()
        self.log = CpLog()

        self.printerID = printerThread.printerID

        self.states = CpPrinterStates(self)
        self.current_state = self.states.INITIALIZE

        # Gradually increasing backoff as more errors occur
        self.waitRetryBackoff = [5, 15, 30, 60]
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time
        self.printer_command_buffer = ""  #stores incomplete printer commands

        #An ack isn't expected until a heartbeat is sent
        self.heartbeat_ack_pending = False
        self.last_heartbeat_time = time.time()

        #Contains pending acks for print commands
        self.ack_queue = Queue.Queue(128)

        self.printerThread = printerThread

        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

    def get_retry_backoff(self, num_errors):
        """
            Gets the current retry backoff time based on the
            number of errors encountered.
        """
        return self.waitRetryBackoff[num_errors % 4]

    def enter_state(self, new_state):
        """
            Sets the next state to new_state
            A call to this will not immediately change state. The next
            state will execute upon return from the current state.
        """
        self.current_state = new_state
        self.STATEFUNC = self.current_state[CpStateKey.FUNCTION]
        self.begin_state_time = datetime.now()
        self.timeout = self.current_state[CpStateKey.TIMEOUT]

        if CpDefs.LogVerboseInet:
            print 'enter_state: (', self.current_state[CpStateKey.NAME], ')'

    def state_timedout(self):
        if (datetime.now() - self.begin_state_time).seconds >= self.timeout:

            if CpDefs.LogVerboseInet:
                print 'state_timeout: (', self.current_state[
                    CpStateKey.NAME], ')'

            return True
        else:
            return False

    def reset_state_timeout(self):
        self.begin_state_time = datetime.now()

    def inet_init(self):
        try:
            self.remoteIp = socket.gethostbyname(self.host)
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            if CpDefs.LogVerboseInet:
                print 'inet_init: successful (%s)' % self.remoteIp

            self.initialized = True
            self.enter_state(self.states.CONNECT)

            return True
        except socket.gaierror:
            self.log.logError(
                'inet_init: failed (hostname could not be resolved)')
            print 'inet_init: failed (hostname could not be resolved)'
        except socket.error, e:
            for error in e:
                print "error: ", e
            self.log.logError('inet_init: failed (other)')
            print 'inet_init: failed (other)'

        # If we get this far we received an error
        self.handle_inet_init_error()

        return False
コード例 #8
0
ファイル: cpinet.py プロジェクト: CPHT/echobaseppp
class CpInet(threading.Thread):
    
    def __init__(self, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32)
        #self.data_buffer = Queue.Queue(128)
        self.inet_timeout = 0
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.inetBusy = False
        self.inetResult = CpInetResult()
        self.inetToken = ""
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.route = CpInetDefs.INET_ROUTE
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.state = CpInetState.CLOSED
        self.state_timeout = time.time()
        self.exponential_backoff = 30
        self.log = CpLog()
        self.state_cb = None
        #self.data_buffer = ""
        threading.Thread.__init__(self)
    
    def setStateChangedCallback(self, callback):
        self.state_cb = callback   
                        
    def lookupStateName(self, index):
        if(index == 0):
            return "INITIALIZED"
        elif(index == 1):
            return "IDLE"
        elif(index == 2):
            return "CONNECTED"
        elif(index == 3):
            return "CLOSED"
        elif(index == 4):
            return "SLEEP"  
        elif(index == 5):
            return "WAITNETWORKINTERFACE"
                   
    def enter_state(self, new_state, timeout):
        print 'enter_state: ', self.lookupStateName(new_state)
            
        self.state = new_state
        self.state_timeout = time.time() + timeout
    
    def state_timedout(self):
        if(time.time() >= self.state_timeout):
            print 'state_timeout: (', self.lookupStateName(self.state), ')'
            return True
        else:
            return False
        
    def reset_state_timeout(self, timeout):
        print 'reset_state_timeout:'
        self.state_timeout = time.time() + timeout    
    
    def run(self):
        self._target(*self._args)
        
    def shutdown_thread(self):
        print 'shutting down CpInet...'
        self.inet_close() # New code added
        self.__lock.acquire()
        self.closing = True
        self.__lock.release()
    

    def init_socket(self):
        try:
            self.remoteIp = socket.gethostbyname(self.host)
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print 'init_socket: successful (%s)' %self.remoteIp
            return True
        except socket.gaierror:
            self.log.logError('init_socket: failed (hostname could not be resolved)')
            print 'init_socket: failed (hostname could not be resolved)'
            return False
        except:
            self.log.logError('init_socket: failed (other)')
            print 'init_socket: failed (other)'
            return False
              
    def inet_connect(self):
           
        try:
            self.sock.connect((self.remoteIp, self.port))
            print 'inet_connect: successful'
            return True
        except:
            self.log.logError('inet_connect: failed')
            print 'inet_connect: failed'
            return False
        
    def inet_send(self, packet):
           
        postData = CpInetDefs.INET_HTTPPOST % (CpInetDefs.INET_ROUTE, CpInetDefs.INET_HOST, len(packet), packet)
            
        print 'inet_send: (',self.remoteIp, ':', self.port, ')'
        
        if CpDefs.LogPacketLevel == True:
            print 'inet_send: ', postData
        
        try:
            byteCount = self.sock.send(postData)
        except socket.error:
            self.log.logError('inet_send: failed')
            print 'inet_send: failed'
            return False
    
        print 'Packet sent successfully %d' % byteCount    
        reply = self.sock.recv(4096)
        
        #print 'inet_send (reply): ', reply
        
        result = CpInetResultCode()
        
        result = self.inet_parse_result(reply)
        
        if (result.ResultCode == CpInetResultCode.RESULT_OK):
            #print 'ResultCode=CpInetResultCode.RESULT_OK'
            print 'inet_send: successful'
            return True
        elif (result.ResultCode == CpInetResultCode.RESULT_ERROR):
            #print 'ResultCode=CpInetResultCode.RESULT_ERROR'
            self.log.logError('inet_parse_result: %s' % result.Data)
            print 'inet_send: failed (error)'
            return False
        else:
            self.log.logError('inet_parse_result: %s' % result.Data)
            print 'inet_send: failed (unknown)'
            return False
     
        
    def inet_close(self):
           
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            print 'inet_close: successful'
            return True
        except:
            self.log.logError('inet_close: failed')
            print 'inet_close: failed'
            return False      
              
    def toggleState(self, state):
        if (self.state_cb != None):
            self.state_cb(state)    
            
    def inet_handler(self):
        
        retry = 0
        # Start out closed
        self.enter_state(CpInetState.CLOSED, 1)
        
        while not self.closing:
            
            if(self.state == CpInetState.CLOSED):
                # Make sure we have established a connection
                if(self.init_socket() == True):
                    self.enter_state(CpInetState.INITIALIZED, 1)
                    time.sleep(.05)
                    continue
            elif(self.state == CpInetState.INITIALIZED):
                self.toggleState(CpSystemState.CONNECT)
                if self.inet_connect() == True:
                    self.enter_state(CpInetState.CONNECTED, 30)
                    
                    time.sleep(.05)
                    continue
            elif(self.state == CpInetState.CONNECTED):
                # Allow the connected state to wait at least 30s before
                # going to idle. This will keep us from bouncing between
                # idle and connected states thus decreasing latency.
                # Reset the timer for each new message
                if(self.state_timedout() == True):
                    self.toggleState(CpSystemState.IDLE)
                    self.enter_state(CpInetState.IDLE, 30)
                    continue
                if (self.commands.qsize() > 0):
                    self.toggleState(CpSystemState.SEND)
                    self.reset_state_timeout(30)
                    print 'Command found'
                    packet = self.commands.get(True)
                    
                    if(self.inet_send(packet) == True):
                        self.commands.task_done()
                    else:
                        # Keep track of send failures
                        pass

            elif(self.state == CpInetState.IDLE):
                # Check to see if there is a queued message
                if (self.commands.qsize() > 0):
                    self.enter_state(CpInetState.CONNECTED, 30)
                    
                # Check for idle timeout then close connection
                if(self.state_timedout() == True):
                    self.inet_close()
                    self.toggleState(CpSystemState.SLEEP)
                    self.enter_state(CpInetState.SLEEP, 60)
                pass
            elif(self.state == CpInetState.SLEEP):
                # Check to see if there is a queued message
                if (self.commands.qsize() > 0):
                    self.enter_state(CpInetState.CLOSED, 1)
                    continue
                
                # Check to wake send ping once every 60s
                if(self.state_timedout() == True):
                    self.enter_state(CpInetState.CLOSED, 1)
                    continue

                
            
        '''
        if(self.inet_test() == True ):
            
            tmp_buffer = ""
        
            while not self.closing:
                
                if (self.commands.qsize() > 0):
                    print 'Command found'
                    packet = self.commands.get(True)
                    self.commands.task_done()
                    self.inet_send(packet)
                    continue
                
                time.sleep(2)
        '''
                    
    def enqueue_packet(self, packet):
        try:
            #self.inetBusy = True
            self.commands.put(packet, block=True, timeout=1)
        except:
            self.__lock.acquire()
            print "CpInet commands queue is full"
            self.__lock.release()

    def set_timeout(self, timeout):
        self.inet_timeout = datetime.now() + timeout
    
    def is_timeout(self):
        if(datetime.now() >= self.rf_timeout):
            return True
        else:
            return False
    '''
    def is_error(self, token):        
        if(token.find(CpInetResponses.TOKEN_HTTPERROR) > -1):
            return True
        else:
            return False
    '''
        
    def inet_parse_result(self, result):
        
        inet_result = CpInetResult()
        
        if(result.find(CpInetResponses.TOKEN_HTTPOK) > -1):
            inet_result.Data = result
            inet_result.ResultCode = CpInetResultCode.RESULT_OK
        elif(result.find(CpInetResponses.TOKEN_HTTPERROR) > -1):
            inet_result.Data = result
            inet_result.ResultCode = CpInetResultCode.RESULT_ERROR
        else:
            inet_result.Data = result
            inet_result.ResultCode = CpInetResultCode.RESULT_UNKNOWN
                
        return inet_result
            
    
  
  
  
    def inet_test(self):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.remoteIp, self.port))
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            return True
        except:
            self.log.logError('inet_test:')
            return False
コード例 #9
0
ファイル: cdksim.py プロジェクト: erudisill/cdksim
class CpInet(threading.Thread):
    def __init__(self, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False  # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32)
        #self.data_buffer = Queue.Queue(128)
        self.inet_timeout = 0
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.inetBusy = False
        self.inetResult = CpInetResult()
        self.inetToken = ""
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.route = CpInetDefs.INET_ROUTE
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.current_state = CpInetState.INITIALIZE
        self.inetError = CpInetError()
        self.state_timeout = time.time()
        self.exponential_backoff = 30
        self.log = CpLog()
        self.state_cb = None
        self.retries = 1
        self.waitRetryBackoff = {1: 5, 2: 15, 3: 30}
        #self.waitRetryBackoff = {1:1, 2:2, 3:3} # Test timeouts to speed up testing
        self.stateMaxRetries = 3
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time

        self.fmap = {
            0: self.init_socket,
            1: self.inet_idle,
            2: self.inet_connect,
            3: self.inet_close,
            4: self.inet_sleep,
            5: self.inet_send,
            6: self.inet_waitnetworkinterface
        }

        threading.Thread.__init__(self)

    def get_queue_depth(self):
        return self.commands.qsize()

    def get_current_state(self):
        return self.lookupStateName(self.current_state)

    def get_inet_stats(self):
        return self.inet_stats

    def setStateChangedCallback(self, callback):
        self.state_cb = callback

    def lookupStateName(self, index):
        if (index == 0):
            return "INITIALIZE"
        elif (index == 1):
            return "IDLE"
        elif (index == 2):
            return "CONNECT"
        elif (index == 3):
            return "CLOSE"
        elif (index == 4):
            return "SLEEP"
        elif (index == 5):
            return "SEND"
        elif (index == 6):
            return "WAITNETWORKINTERFACE"

    def enter_state(self, new_state, timeout):
        self.current_state = new_state
        self.STATEFUNC = self.fmap[self.current_state]
        self.timestamp = datetime.now()
        self.timeout = timeout

        #if(CpDefs.LogVerboseInet):
        print 'enter_state: (', self.lookupStateName(self.current_state), ')'

        # Set the led pattern via state_cb
        # Hack if statement to prevent state_cb from being called before
        # setStateChangedCallback is set by cptaskmanager
        if (self.state_cb == None):
            return
        else:
            self.state_cb(new_state)

    def exit_state(self):
        self.current_state = 0
        self.STATEFUNC = 0
        self.timeout = 0.0

    def state_timedout(self):
        if ((datetime.now() - self.timestamp).seconds >= self.timeout):

            if (CpDefs.LogVerboseInet):
                print 'state_timeout: (', self.lookupStateName(
                    self.current_state), ')'

            return True
        else:
            return False

    def reset_state_timeout(self):
        self.timestamp = datetime.now()

    def inet_handler(self):

        if (CpDefs.WatchdogWaitNetworkInterface):
            # Start out waiting for network interface
            self.enter_state(CpInetState.WAITNETWORKINTERFACE,
                             CpInetTimeout.WAITNETWORKINTERFACE)
        else:
            # Start out initializing (Use Case for testing without watchdog)
            self.enter_state(CpInetState.INITIALIZE, CpInetTimeout.INITIALIZE)

        while not self.closing:
            if (self.STATEFUNC != 0):
                self.STATEFUNC()
            time.sleep(.0001)

    def run(self):
        self._target(*self._args)

    def shutdown_thread(self):
        print 'shutting down CpInet...'
        self.inet_close()  # New code added
        self.__lock.acquire()
        self.closing = True
        self.__lock.release()

    def init_socket(self):
        try:
            self.remoteIp = socket.gethostbyname(self.host)
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            if (CpDefs.LogVerboseInet):
                print 'init_socket: successful (%s)' % self.remoteIp

            self.enter_state(CpInetState.CONNECT, CpInetTimeout.CONNECT)
            return True
        except socket.gaierror:
            self.log.logError(
                'init_socket: failed (hostname could not be resolved)')
            print 'init_socket: failed (hostname could not be resolved)'
        except:
            self.log.logError('init_socket: failed (other)')
            print 'init_socket: failed (other)'

        # If we get this far we received an error
        self.handle_init_socket_error()

        return False

    def handle_init_socket_error(self):

        # ******** BEGIN ERROR HANDLING ********

        # If we get this far we received an error
        self.inetError.InitializeErrors += 1
        # Updated Statistics
        self.inet_stats.InitErrors += 1

        if (self.inetError.InitializeErrors > self.inetError.InitializeMax):
            print 'Max Initialize Errors'
            # Reset Error Counter
            self.inetError.InitializeErrors = 0
            # Handle Max Errors
            # TODO: TEST BEFORE PROD

            # Check to see if we need to update watchdog
            # if not we are in test mode and just want to remain in
            # init_socket indefinately
            if (CpDefs.WatchdogWaitNetworkInterface):
                self.watchdog_set_status(CpWatchdogStatus.Error)
                self.enter_state(CpInetState.WAITNETWORKINTERFACE,
                                 CpInetTimeout.WAITNETWORKINTERFACE)

            return False

        # Allow some settle time before trying again
        print 'Wait Retry Backoff %d sec.' % self.waitRetryBackoff[
            self.inetError.InitializeErrors]
        time.sleep(self.waitRetryBackoff[self.inetError.InitializeErrors])

        # ******** END ERROR HANDLING ********

    def inet_connect(self):

        try:
            self.sock.connect((self.remoteIp, self.port))
            # New Code for Timeout
            self.sock.settimeout(CpInetDefs.INET_TIMEOUT)
            # End New Code for Timeout

            if (CpDefs.LogVerboseInet):
                print 'inet_connect: successful'

            self.enter_state(CpInetState.IDLE, CpInetTimeout.IDLE)
            if CpDefs.WatchdogWaitNetworkInterface == True:
                self.watchdog_set_status(CpWatchdogStatus.Success)
            return True
        except:
            self.log.logError('inet_connect: failed')
            print 'inet_connect: failed'

        # If we get this far we received an error
        self.handle_inet_connect_error()

        return False

    def handle_inet_connect_error(self):

        # ******** BEGIN ERROR HANDLING ********

        self.inetError.ConnectErrors += 1

        # Updated Statistics
        self.inet_stats.ConnectErrros += 1

        print 'CONNECT FAILED'

        if (self.inetError.ConnectErrors > self.inetError.ConnectMax):
            # Handle Max Errors
            self.inetError.ConnectErrors = 0
            self.enter_state(CpInetState.INITIALIZE, CpInetTimeout.INITIALIZE)
            return False

        # Allow some settle time before trying again
        print 'Wait Retry Backoff %d sec.' % self.waitRetryBackoff[
            self.inetError.ConnectErrors]
        time.sleep(self.waitRetryBackoff[self.inetError.ConnectErrors])

        # ******** END ERROR HANDLING ********

    def inet_send(self):

        # Allow the connected state to wait at least 30s before
        # going to idle. This will keep us from bouncing between
        # idle and connected states thus decreasing latency.
        # Reset the timer for each new message
        if (self.state_timedout() == True):
            self.enter_state(CpInetState.IDLE, CpInetTimeout.IDLE)
            return True

        if (self.commands.qsize() > 0):
            self.reset_state_timeout()

            if (CpDefs.LogVerboseInet):
                print 'Command found'

            packet = self.commands.get(True)

            #if(self.inet_send_packet(packet) == True):
            result = self.inet_send_packet(packet)

            if (result.ResultCode == CpInetResultCode.RESULT_OK):

                # Updated Statistics
                self.inet_stats.Sent += 1
                self.inet_stats.LastSent = time

                if (CpDefs.LogVerboseInet):
                    print 'SEND SUCCESSFUL'

                self.commands.task_done()
            else:
                print 'inet_send error: %s' % result.Data

                if CpDefs.InetSendRetry == True:
                    self.enqueue_packet(packet)
                    self.handle_inet_send_error()
                #print 'tasks in queue %d' % self.commands.qsize()
                #print 'error: ResultCode=(%d) Data=%s ' % (result.ResultCode, result.Data)

            return True
        else:
            # Otherwise we have no new messages and the current
            # state has not yet timed out so return True in order
            # to avoid the error handling
            return True

    def handle_inet_send_error(self):

        # ******** BEGIN ERROR HANDLING ********

        self.inetError.SendErrors += 1

        # Updated Statistics
        self.inet_stats.SendErrors += 1

        print 'SEND FAILED'

        if (self.inetError.SendErrors > self.inetError.SendMax):
            # We have exceeded the maximum allowable attempts so
            # close and reinitialize the connection
            self.inetError.SendErrors = 0
            self.inet_close()
            self.enter_state(CpInetState.INITIALIZE, CpInetTimeout.INITIALIZE)
            return False

        # Allow some settle time before trying again
        print 'Wait Retry Backoff %d sec.' % self.waitRetryBackoff[
            self.inetError.SendErrors]
        time.sleep(self.waitRetryBackoff[self.inetError.SendErrors])

        # ******** END ERROR HANDLING ********

    # inet_send_packet is explicitly called by inet_send
    def inet_send_packet(self, packet):

        # Setup the HTTP request
        postData = CpInetDefs.INET_HTTPPOST % (
            self.route, CpInetDefs.INET_HOST, len(packet), packet)
        #postData = CpInetDefs.INET_HTTPPOST % (CpInetDefs.INET_ROUTE, CpInetDefs.INET_HOST, len(packet), packet)
        #postData = CpInetDefs.INET_HTTPPOST % (packet.Route, CpInetDefs.INET_HOST, len(packet.Data), packet.Data)

        print "PostData: ", postData
        result = CpInetResultCode()

        if (CpDefs.LogVerboseInet):
            print 'inet_send: (', self.remoteIp, ':', self.port, ')'
            print 'inet_send: ', postData

        # Send the HTTP request
        try:
            byteCount = self.sock.send(postData)
        except socket.error, e:
            result.ResultCode = CpInetResultCode.RESULT_SCKSENDERROR
            result.Data = e.args[0]
            self.log.logError('inet_send: failed')
            print 'inet_send: failed'
            return result

        # Process the response
        try:
            reply = self.sock.recv(4096)
        except socket.error, e:
            err = e.args[0]
            if err == 'timed out':
                result.ResultCode = CpInetResultCode.RESULT_SCKTIMEOUT
                print 'socket timeout exception'
            else:
                result.ResultCode = CpInetResultCode.RESULT_SCKRECVERROR

            result.Data = e.args[0]

            self.log.logError('inet_send: failed')
            print 'inet_send: failed'
            return result
コード例 #10
0
ファイル: main.py プロジェクト: CPHT/echobaseppp
        while(consoleThread.isAlive()):
    
            time.sleep(.005)
    
        print 'Exiting App...'
        exit()
        
        
        
      
            
if __name__ == '__main__':
    
    if CpDefs.LogToStdOut == True:
        # Route standard out to a log file
        log = CpLog()
        log.logStdOut()
    
    print "one"
    print "two"
    print "three"
    main(sys.argv[1:])
    

    '''
    rfThread = CpRf(rfDataReceived)
    rfThread.start()
    
    inetThread = CpInet(inetDataReceived)
    inetThread.start()
    
コード例 #11
0
class CpPrinterService(threading.Thread):

    def __init__(self, printerThread, inetResponseCallbackFunc=None, *args):
        self._target = self.inet_handler
        self._args = args
        self.__lock = threading.Lock()
        self.closing = False # A flag to indicate thread shutdown
        self.commands = Queue.Queue(32) # Commands for this script to handle
        self.inetResponseCallbackFunc = inetResponseCallbackFunc
        self.host = CpInetDefs.INET_HOST
        self.port = CpInetDefs.INET_PORT
        self.sock = None
        self.remoteIp = None
        self.initialized = False
        self.inet_error = CpInetError()
        self.log = CpLog()

        self.printerID = printerThread.printerID

        self.states = CpPrinterStates(self)
        self.current_state = self.states.INITIALIZE

        # Gradually increasing backoff as more errors occur
        self.waitRetryBackoff = [5, 15, 30, 60]
        self.inet_stats = CpInetStats()
        self.inet_stats.LastSent = time
        self.printer_command_buffer = "" #stores incomplete printer commands

        #An ack isn't expected until a heartbeat is sent
        self.heartbeat_ack_pending = False
        self.last_heartbeat_time = time.time()

        #Contains pending acks for print commands
        self.ack_queue = Queue.Queue(128)

        self.printerThread = printerThread

        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

    def get_retry_backoff(self, num_errors):
        """
            Gets the current retry backoff time based on the
            number of errors encountered.
        """
        return self.waitRetryBackoff[num_errors % 4]
        

    def enter_state(self, new_state):
        """
            Sets the next state to new_state
            A call to this will not immediately change state. The next
            state will execute upon return from the current state.
        """
        self.current_state = new_state
        self.STATEFUNC = self.current_state[CpStateKey.FUNCTION]
        self.begin_state_time = datetime.now()
        self.timeout = self.current_state[CpStateKey.TIMEOUT]

        if CpDefs.LogVerboseInet:
            print 'enter_state: (', self.current_state[CpStateKey.NAME], ')'

    def state_timedout(self):
        if (datetime.now() - self.begin_state_time).seconds >= self.timeout:

            if CpDefs.LogVerboseInet:
                print 'state_timeout: (', self.current_state[CpStateKey.NAME], ')'

            return True
        else:
            return False

    def reset_state_timeout(self):
        self.begin_state_time = datetime.now()

    def inet_init(self):
        try:
            self.remoteIp = socket.gethostbyname(self.host)
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            if CpDefs.LogVerboseInet:
                print 'inet_init: successful (%s)' %self.remoteIp

            self.initialized = True
            self.enter_state(self.states.CONNECT)

            return True
        except socket.gaierror:
            self.log.logError('inet_init: failed (hostname could not be resolved)')
            print 'inet_init: failed (hostname could not be resolved)'
        except socket.error, e:
            for error in e:
                print "error: ", e
            self.log.logError('inet_init: failed (other)')
            print 'inet_init: failed (other)'

        # If we get this far we received an error
        self.handle_inet_init_error()

        return False