Advertisement
gahcep

Python WaitableTimer

Mar 8th, 2012
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 23.73 KB | None | 0 0
  1. # Copyright (c) 2012 Sergey Danielyan a.k.a gahcep
  2. #
  3. # Permission is hereby granted, free of charge, to any person
  4. # obtaining a copy of this software and associated documentation
  5. # files (the "Software"), to deal in the Software without
  6. # restriction, including without limitation the rights to use,
  7. # copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the
  9. # Software is furnished to do so, subject to the following
  10. # conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be
  13. # included in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  17. # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  19. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  20. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  22. # OTHER DEALINGS IN THE SOFTWARE.
  23.  
  24. from Queue import Queue
  25. from threading import Event, Thread
  26. from time import time, gmtime, strftime
  27.  
  28. ## Limits
  29. PRECISION_MIN               = 0.001
  30. PRECISION_DEFAULT           = 0.001
  31. PRECISION_MAX               = 1
  32. TIMER_INTERVAL_MIN          = 0
  33. TIMER_INTERVAL_MAX          = 3600
  34. TIMER_INTERVAL_INITIAL_MIN  = 1
  35. TIMER_INTERVAL_INITIAL_MAX  = 3600
  36. TIMER_COUNT_MIN             = 0
  37. TIMER_COUNT_MAX             = 10000
  38. SUSPENDED_DELAY_MIN         = 0
  39. SUSPENDED_DELAY_MAX         = 10000
  40. TIMER_QUEUE_SIZE            = 100
  41.  
  42. ## Timer activation options
  43. TIMER_ACTIVATE              = 1
  44. TIMER_NO_ACTIVATE           = 0
  45.  
  46. ## State definitions
  47. TIMER_STATE_IDLE            = 1
  48. TIMER_STATE_INIT            = 2
  49. TIMER_STATE_RUNNINGINITIAL  = 3
  50. TIMER_STATE_RUNNING         = 4
  51. TIMER_STATE_SUSPENDED       = 5
  52. TIMER_STATE_TERMINATED      = 6
  53.  
  54. ## For translate state numerical code
  55. STATE_TO_TEXT = {
  56. 1 : 'TIMER_STATE_IDLE',
  57. 2 : 'TIMER_STATE_INIT',
  58. 3 : 'TIMER_STATE_RUNNINGINITIAL',
  59. 4 : 'TIMER_STATE_RUNNING',
  60. 5 : 'TIMER_STATE_SUSPENDED',
  61. 6 : 'TIMER_STATE_TERMINATED',
  62. }
  63.  
  64. ## Message types
  65. MESSAGE_INIT                = 100
  66. MESSAGE_ACTIVATE            = 101
  67. MESSAGE_DEACTIVATE          = 102
  68. MESSAGE_PAUSE               = 103
  69. MESSAGE_RESUME              = 104
  70. MESSAGE_CHANGE              = 105
  71. MESSAGE_TERMINATE           = 106
  72. MESSAGE_PRECISION           = 107
  73.  
  74. ## Error codes
  75. T_SUCCESS                   = 1000
  76. T_ERROR_INCORRECT_STATE     = 1001
  77. T_ERROR_ALREADY_SWITCHED    = 1002
  78.  
  79. class WaitableTimer(Thread):
  80.    
  81.     def __init__(self,
  82.                  TimerInitialInterval, TimerContinuousInterval,
  83.                  FunctionProc,
  84.                  StartCondition = TIMER_ACTIVATE,
  85.                  TimerCount = TIMER_COUNT_MIN,
  86.                  Precision = PRECISION_DEFAULT,
  87.                  DEBUG = False,
  88.                  PROFILE = False,
  89.                  FunctionArgs = [], FunctionKWArgs = {}
  90.                  ):
  91.        
  92.         ## Had to be the first
  93.         Thread.__init__(self)
  94.        
  95.         # Received parameters
  96.         self.ValidatePrecision(Precision)
  97.         self.ValidateInitialInterval(TimerInitialInterval)
  98.         self.ValidateInterval(TimerContinuousInterval)
  99.         self.ValidateCount(TimerCount)
  100.         ## Function related
  101.         self.__FunctionProc = FunctionProc
  102.         self.__FunctionArgs = FunctionArgs
  103.         self.__FunctionKWArgs = FunctionKWArgs
  104.         ## Debug related
  105.         self.__DEBUG = DEBUG
  106.         self.__PROFILE = PROFILE
  107.         ## Flags        
  108.         self.__IsOneTimeShotTimer = True if self.__TimerInterval == 0 else False
  109.         self.__IsRepeatableTimer = True if self.__TimerCount != 0 else False
  110.        
  111.         # Inner variables
  112.         self.__SuspendedDelay = 0
  113.         self.__State = TIMER_STATE_IDLE
  114.         self.__Error = T_SUCCESS
  115.        
  116.         # Events
  117.         self.__ePauseResume = Event()
  118.         self.__eActivate = Event()
  119.         self.__eDeactivate = Event()
  120.         self.__eInit = Event()
  121.         self.__eTerminate = Event()
  122.        
  123.         # Queue init
  124.         self.__MsgQueue = Queue(TIMER_QUEUE_SIZE)
  125.        
  126.         # Move to first working state
  127.         self.__MsgQueue.put_nowait((MESSAGE_INIT, 0, 0))
  128.        
  129.         # Or even further
  130.         if StartCondition == TIMER_ACTIVATE:
  131.             self.__MsgQueue.put_nowait((MESSAGE_ACTIVATE, 0, 0))
  132.    
  133.     def run(self):        
  134.        
  135.         ## Variables for saving/restoring values
  136.         SavedState = TIMER_STATE_IDLE
  137.         SavedTime = 0
  138.        
  139.         ## Working variables
  140.         InitialTime = 0
  141.         TimeoutMark = 0
  142.                
  143.         ## Main cycle
  144.         while not self.__eTerminate.is_set():
  145.            
  146.             ##################################
  147.             ##### Message Processing Loop ####
  148.             ##################################
  149.             while not self.__MsgQueue.empty():
  150.                 message = self.__MsgQueue.get_nowait()
  151.                
  152.                 ## MESSAGE_INIT
  153.                 if message[0] == MESSAGE_INIT:
  154.                     self.__DebugPrint(">> Received MESSAGE_INIT")
  155.                     self.__eInit.set()                    
  156.                
  157.                 ## MESSAGE_CHANGE
  158.                 elif message[0] == MESSAGE_CHANGE:
  159.                     self.__DebugPrint(">> Received MESSAGE_CHANGE")
  160.                     self.ValidateInitialInterval(message[1])
  161.                     self.ValidateInterval(message[2])
  162.                    
  163.                     if self.__State == TIMER_STATE_RUNNINGINITIAL:
  164.                         TimeoutMark += self.__TimerInitialInterval - TimeoutMark
  165.                     elif self.__State == TIMER_STATE_RUNNING:
  166.                         TimeoutMark += self.__TimerInterval - TimeoutMark
  167.                
  168.                 ## MESSAGE_PRECISION
  169.                 elif message[0] == MESSAGE_PRECISION:
  170.                     self.__DebugPrint(">> Received MESSAGE_PRECISION")
  171.                     self.ValidatePrecision(message[1])
  172.                
  173.                 ## MESSAGE_ACTIVATE
  174.                 elif message[0] == MESSAGE_ACTIVATE:
  175.                     self.__DebugPrint(">> Received MESSAGE_ACTIVATE")
  176.                     self.__eActivate.set()
  177.                    
  178.                 ## MESSAGE_DEACTIVATE
  179.                 elif message[0] == MESSAGE_DEACTIVATE:
  180.                     self.__DebugPrint(">> Received MESSAGE_DEACTIVATE")
  181.                     self.__eDeactivate.set()
  182.                    
  183.                 ## MESSAGE_PAUSE
  184.                 elif message[0] == MESSAGE_PAUSE:
  185.                     self.__DebugPrint(">> Received MESSAGE_PAUSE")
  186.                     self.__ePauseResume.set()
  187.                     self.ValidateDelay(message[1])
  188.                    
  189.                 ## MESSAGE_RESUME
  190.                 elif message[0] == MESSAGE_RESUME:
  191.                     self.__DebugPrint(">> Received MESSAGE_RESUME")
  192.                     self.__ePauseResume.set()
  193.                     self.__SuspendedDelay = 0
  194.                
  195.                 ## MESSAGE_TERMINATE
  196.                 elif message[0] == MESSAGE_TERMINATE:
  197.                     self.__DebugPrint(">> Received MESSAGE_TERMINATE")
  198.                     self.__eTerminate.set()
  199.            
  200.             ##################################
  201.             ##### State Processing Loop ######
  202.             ##################################
  203.            
  204.             ## TIMER_STATE_IDLE
  205.             if self.__State == TIMER_STATE_IDLE:
  206.                 self.__DebugPrint("Current State: TIMER_STATE_IDLE")
  207.                 if self.__eInit.is_set():
  208.                     self.__DebugPrint("Changing the state to TIMER_STATE_INIT")
  209.                     self.__State = TIMER_STATE_INIT
  210.                     self.__eInit.clear()
  211.                     continue
  212.            
  213.             ## TIMER_STATE_INIT
  214.             elif self.__State == TIMER_STATE_INIT:
  215.                 self.__DebugPrint("Current State: TIMER_STATE_INIT")
  216.                
  217.                 if self.__eActivate.is_set():
  218.                     self.__DebugPrint("Changing the state to TIMER_STATE_RUNNINGINITIAL")
  219.                     self.__State = TIMER_STATE_RUNNINGINITIAL
  220.                     self.__eActivate.clear()
  221.                     TimeoutMark = self.__TimerInitialInterval
  222.                     InitialTime = time()
  223.                     continue
  224.            
  225.             ## TIMER_STATE_SUSPENDED
  226.             elif self.__State == TIMER_STATE_SUSPENDED:
  227.                 self.__DebugPrint("Current State: TIMER_STATE_SUSPENDED")
  228.                 if self.__eTerminate.is_set():
  229.                     self.__DebugPrint("Terminating a timer")
  230.                     continue
  231.                
  232.                 if self.__eDeactivate.is_set():
  233.                     self.__DebugPrint("Changing the state to TIMER_STATE_INIT")
  234.                     self.__eDeactivate.clear()
  235.                     self.__State = TIMER_STATE_INIT
  236.                     continue
  237.                
  238.                 if self.__ePauseResume.is_set():
  239.                     self.__DebugPrint("Restoring the state after Pause()")
  240.                     self.__State = SavedState
  241.                     # Increase the initial value with the value of delay
  242.                     # "time() - SavedTime" - amount of delay
  243.                     InitialTime += time() - SavedTime
  244.                     self.__ePauseResume.clear()
  245.                     continue
  246.                
  247.                 if self.__SuspendedDelay != 0:
  248.                     if (time() - SavedTime) >= self.__SuspendedDelay:
  249.                         self.__DebugPrint("SuspendedDelay is over now")
  250.                         # Automatically check in the flag if delay is over
  251.                         self.__ePauseResume.set()
  252.                         continue
  253.  
  254.             ## TIMER_STATE_RUNNINGINITIAL
  255.             elif self.__State == TIMER_STATE_RUNNINGINITIAL:
  256.                 self.__DebugPrint("Current State: TIMER_STATE_RUNNINGINITIAL")
  257.                 # Preinitial processing due to immediately exit from the cycle
  258.                 # ignoring the fact, that FunctionProc might be just invoked
  259.                 if self.__eTerminate.is_set():
  260.                     self.__DebugPrint("Terminating a timer")
  261.                     continue
  262.                
  263.                 if self.__eDeactivate.is_set():
  264.                     self.__DebugPrint("Changing the state to TIMER_STATE_INIT")
  265.                     self.__eDeactivate.clear()
  266.                     self.__State = TIMER_STATE_INIT
  267.                     continue
  268.                
  269.                 if self.__ePauseResume.is_set():
  270.                     self.__DebugPrint("Changing the state to TIMER_STATE_SUSPENDED")
  271.                     SavedState = self.__State
  272.                     SavedTime = time()
  273.                     self.__State = TIMER_STATE_SUSPENDED
  274.                     self.__ePauseResume.clear()
  275.                     continue
  276.                
  277.                 if (time() - InitialTime) >= TimeoutMark:
  278.                     self.__DebugPrint("Invoking a FUNCTION")
  279.                     self.__State = TIMER_STATE_RUNNING
  280.                     self.__FunctionProc(*self.__FunctionArgs, **self.__FunctionKWArgs)
  281.                     TimeoutMark = self.__TimerInterval
  282.                     InitialTime = time()
  283.                     if self.__IsOneTimeShotTimer:
  284.                         self.__DebugPrint("Terminating a One-Time-Shot timer")
  285.                         self.__eTerminate.set()
  286.                     elif self.__IsRepeatableTimer:
  287.                         self.__TimerCount -= 1
  288.                         if (self.__TimerCount <= 0):
  289.                             self.__DebugPrint("Terminating a Repeatable timer")
  290.                             self.__eTerminate.set()
  291.                             continue
  292.                         else:
  293.                             self.__DebugPrint("Remained invocation function calls: " + repr(self.__TimerCount))
  294.                     continue
  295.                
  296.             ## TIMER_STATE_RUNNING
  297.             elif self.__State == TIMER_STATE_RUNNING:
  298.                 self.__DebugPrint("Current State: TIMER_STATE_RUNNING")
  299.                 # Preinitial processing due to immediately exit from the cycle
  300.                 # ignoring the fact, that FunctionProc might be just invoked
  301.                 if self.__eTerminate.is_set():
  302.                     self.__DebugPrint("Terminating a timer")
  303.                     continue
  304.                
  305.                 if self.__eDeactivate.is_set():
  306.                     self.__DebugPrint("Changing the state to TIMER_STATE_INIT")
  307.                     self.__eDeactivate.clear()
  308.                     self.__State = TIMER_STATE_INIT
  309.                     continue
  310.                
  311.                 if self.__ePauseResume.is_set():
  312.                     self.__DebugPrint("Changing the state to TIMER_STATE_SUSPENDED")
  313.                     SavedState = self.__State
  314.                     SavedTime = time()
  315.                     self.__State = TIMER_STATE_SUSPENDED
  316.                     self.__ePauseResume.clear()
  317.                     continue
  318.                
  319.                 if (time() - InitialTime) >= TimeoutMark:
  320.                     self.__DebugPrint("Invoking a FUNCTION")
  321.                     self.__FunctionProc(*self.__FunctionArgs, **self.__FunctionKWArgs)
  322.                     InitialTime = time()
  323.                     if self.__IsRepeatableTimer:
  324.                         self.__TimerCount -= 1
  325.                         if (self.__TimerCount <= 0):
  326.                             self.__DebugPrint("Terminating a Repeatable timer")
  327.                             self.__eTerminate.set()
  328.                             continue
  329.                         else:
  330.                             self.__DebugPrint("Remained invocation function calls: " + repr(self.__TimerCount))
  331.            
  332.             if not self.__eTerminate.is_set():
  333.                 self.__eTerminate.wait(self.__Precision)
  334.             else:
  335.                 self.__DebugPrint("Terminating a timer")
  336.  
  337.         self.__State = TIMER_STATE_TERMINATED
  338.         self.__DebugPrint("Current State: TIMER_STATE_TERMINATED")
  339.    
  340.     ############ Decorator ##############
  341.     def Validate(Minimum, Maximum):
  342.         ## Dynamically creating a decorator
  343.         def Decorator(Function):
  344.             ## Function to call
  345.             def WrapFunction(self, Value):
  346.                 Value = Minimum if Value < Minimum else Maximum if Value > Maximum else Value
  347.                 ## Function invocation
  348.                 Function(self, Value)
  349.             return WrapFunction
  350.         return Decorator
  351.    
  352.     ########### Validators ################
  353.     @Validate(TIMER_INTERVAL_INITIAL_MIN, TIMER_INTERVAL_INITIAL_MAX)
  354.     def ValidateInitialInterval(self, Value):
  355.         self.__TimerInitialInterval = Value
  356.    
  357.     @Validate(TIMER_INTERVAL_MIN, TIMER_INTERVAL_MAX)
  358.     def ValidateInterval(self, Value):
  359.         self.__TimerInterval = Value
  360.    
  361.     @Validate(PRECISION_MIN, PRECISION_MAX)
  362.     def ValidatePrecision(self, Value):
  363.         self.__Precision = Value
  364.    
  365.     @Validate(TIMER_COUNT_MIN, TIMER_COUNT_MAX)
  366.     def ValidateCount(self, Value):
  367.         self.__TimerCount = Value
  368.            
  369.     @Validate(SUSPENDED_DELAY_MIN, SUSPENDED_DELAY_MAX)
  370.     def ValidateDelay(self, Value):
  371.         self.__SuspendedDelay = Value
  372.        
  373.     ########## Getter/Setter functions #########
  374.     def GetPrecision(self):
  375.         return self.__Precision                
  376.    
  377.     def GetState(self):
  378.         return self.__State
  379.    
  380.     def GetError(self):
  381.         return self.__Error
  382.    
  383.     ########### Output Debug information ##########
  384.     def __OutputErrorState(self, RequiredTimerState = [], Invert=False):
  385.         PrintString = "Error: wrong state: should be "
  386.         CondCount = len(RequiredTimerState)
  387.         if not Invert:
  388.             for index, nextstate in enumerate(RequiredTimerState):
  389.                 PrintString += STATE_TO_TEXT[nextstate]
  390.                 if index != (CondCount - 1): PrintString += " or "
  391.             PrintString += " instead of "
  392.             PrintString += STATE_TO_TEXT[self.__State]
  393.         else:
  394.             PrintString += "anything except of "
  395.             PrintString += STATE_TO_TEXT[RequiredTimerState[0]]
  396.         return PrintString
  397.    
  398.     def __DebugPrint(self, Message):
  399.         if self.__DEBUG:
  400.             if self.__PROFILE:
  401.                 print strftime("[%H:%M:%S.", gmtime()) + (("%.3f" % time()).split("."))[1] + "]\t",
  402.             print Message
  403.    
  404.     ########## Behaviour functions ###########
  405.     def SetChange(self, Initial, Interval):
  406.         self.__DebugPrint("SetChange(): In function")
  407.        
  408.         if self.__State != TIMER_STATE_TERMINATED:
  409.             self.__MsgQueue.put_nowait((MESSAGE_CHANGE, Initial, Interval))
  410.             self.__DebugPrint("SetChange(): Notice: message is sent")
  411.             self.__Error = T_SUCCESS
  412.             return True
  413.         else:
  414.             self.__DebugPrint("SetChange(): " + self.__OutputErrorState([TIMER_STATE_TERMINATED], Invert=True))
  415.             self.__Error = T_ERROR_INCORRECT_STATE
  416.             return False
  417.    
  418.     def SetPrecision(self, Precision):
  419.         self.__DebugPrint("SetPrecision(): In function")
  420.        
  421.         if self.__State != TIMER_STATE_TERMINATED:
  422.             self.__MsgQueue.put_nowait((MESSAGE_PRECISION, Precision, 0))
  423.             self.__DebugPrint("SetPrecision(): Notice: message is sent")
  424.             self.__Error = T_SUCCESS
  425.             return True
  426.         else:
  427.             self.__DebugPrint("SetPrecision(): " + self.__OutputErrorState([TIMER_STATE_TERMINATED], Invert=True))
  428.             self.__Error = T_ERROR_INCORRECT_STATE
  429.             return False
  430.    
  431.     ## EXPERIMENTAL ##########################
  432.     def SetTimerFuncBehaviour(self, FunctionResult, FunctionAction,
  433.                               FunctionType = None, FunctionValue = None):
  434.         self.__DebugPrint("SetTimerFuncBehaviour(): In function")
  435.        
  436.         # There is no any DisableStateCheck flag, so it has to be a right state - INIT
  437.         if self.__State != TIMER_STATE_INIT:
  438.             self.__DebugPrint("SetTimerFuncBehaviour(): " + self.__OutputErrorState([TIMER_STATE_INIT], Invert=True))
  439.             self.__Error = T_ERROR_INCORRECT_STATE
  440.             return False
  441.         else:
  442.             self.__FunctionResult = FunctionResult
  443.             self.__FunctionAction = FunctionAction
  444.             self.__FunctionType = FunctionType
  445.             self.__FunctionValue = FunctionValue
  446.    
  447.     ########## Action functions ##############
  448.     def Activate(self, DisableStateCheck = False):
  449.         self.__DebugPrint("Activate(): In function")
  450.        
  451.         if DisableStateCheck:
  452.             self.__MsgQueue.put_nowait((MESSAGE_ACTIVATE, 0, 0))
  453.             self.__DebugPrint("Activate(): Notice: message is sent")
  454.             self.__Error = T_SUCCESS
  455.             return True
  456.        
  457.         elif (self.__State == TIMER_STATE_RUNNING) or (self.__State == TIMER_STATE_RUNNINGINITIAL):
  458.             self.__DebugPrint("Activate(): Warning: already in RUNNING mode")
  459.             self.__Error = T_ERROR_ALREADY_SWITCHED
  460.             return False
  461.        
  462.         elif (self.__State == TIMER_STATE_INIT) or (self.__State == TIMER_STATE_IDLE):
  463.             self.__MsgQueue.put_nowait((MESSAGE_ACTIVATE, 0, 0))
  464.             self.__DebugPrint("Activate(): Notice: message is sent")
  465.             self.__Error = T_SUCCESS
  466.             return True
  467.         else:
  468.             self.__DebugPrint("Activate(): " + self.__OutputErrorState([TIMER_STATE_INIT, TIMER_STATE_IDLE]))
  469.             self.__Error = T_ERROR_INCORRECT_STATE
  470.             return False
  471.    
  472.     def Pause(self, Wait=0, DisableStateCheck = False):
  473.         self.__DebugPrint("Pause(): In function")
  474.        
  475.         if DisableStateCheck:
  476.             self.__MsgQueue.put_nowait((MESSAGE_PAUSE, Wait, 0))
  477.             self.__DebugPrint("Pause(): Notice: message is sent")
  478.             self.__Error = T_SUCCESS
  479.             return True
  480.        
  481.         elif self.__State == TIMER_STATE_SUSPENDED:
  482.             self.__DebugPrint("Pause(): Warning: already in SUSPENDED mode")
  483.             self.__Error = T_ERROR_ALREADY_SWITCHED
  484.             return False
  485.        
  486.         elif (self.__State == TIMER_STATE_RUNNINGINITIAL) or (self.__State == TIMER_STATE_RUNNING):
  487.             self.__MsgQueue.put_nowait((MESSAGE_PAUSE, Wait, 0))
  488.             self.__DebugPrint("Pause(): Notice: message is sent")
  489.             self.__Error = T_SUCCESS
  490.             return True
  491.         else:
  492.             self.__DebugPrint("Pause(): " + self.__OutputErrorState([TIMER_STATE_RUNNINGINITIAL, TIMER_STATE_RUNNING]))
  493.             self.__Error = T_ERROR_INCORRECT_STATE
  494.             return False
  495.    
  496.     def Resume(self, DisableStateCheck = False):
  497.        
  498.         self.__DebugPrint("Resume(): In function")
  499.        
  500.         if DisableStateCheck:
  501.             self.__MsgQueue.put_nowait((MESSAGE_RESUME, 0, 0))
  502.             self.__DebugPrint("Resume(): Notice: message is sent")
  503.             self.__Error = T_SUCCESS
  504.             return True
  505.        
  506.         elif (self.__State == TIMER_STATE_RUNNINGINITIAL) or (self.__State == TIMER_STATE_RUNNING):
  507.             self.__DebugPrint("Resume(): Warning: already in RUNNING mode")
  508.             self.__Error = T_ERROR_ALREADY_SWITCHED
  509.             return False
  510.        
  511.         elif self.__State == TIMER_STATE_SUSPENDED:
  512.             self.__MsgQueue.put_nowait((MESSAGE_RESUME, 0, 0))
  513.             self.__DebugPrint("Resume(): Notice: message is sent")
  514.             self.__Error = T_SUCCESS
  515.             return True
  516.         else:
  517.             self.__DebugPrint("Resume(): " + self.__OutputErrorState([TIMER_STATE_SUSPENDED]))
  518.             self.__Error = T_ERROR_INCORRECT_STATE
  519.             return False
  520.    
  521.     def Deactivate(self, DisableStateCheck = False):
  522.        
  523.         self.__DebugPrint("Deactivate(): In function")
  524.        
  525.         if DisableStateCheck:
  526.             self.__MsgQueue.put_nowait((MESSAGE_DEACTIVATE, 0, 0))
  527.             self.__DebugPrint("Deactivate(): Notice: message is sent")
  528.             self.__Error = T_SUCCESS
  529.             return True
  530.        
  531.         elif self.__State == TIMER_STATE_INIT:
  532.             self.__DebugPrint("Deactivate(): Warning: already in INIT mode")
  533.             self.__Error = T_ERROR_ALREADY_SWITCHED
  534.             return False
  535.        
  536.         elif (self.__State == TIMER_STATE_SUSPENDED) or (self.__State == TIMER_STATE_RUNNING) or (self.__State == TIMER_STATE_RUNNINGINITIAL):
  537.             self.__MsgQueue.put_nowait((MESSAGE_DEACTIVATE, 0, 0))
  538.             self.__DebugPrint("Deactivate(): Notice: message is sent")
  539.             self.__Error = T_SUCCESS
  540.             return True
  541.         else:
  542.             self.__DebugPrint("Deactivate(): " + self.__OutputErrorState([TIMER_STATE_SUSPENDED, TIMER_STATE_RUNNING, TIMER_STATE_RUNNINGINITIAL]))
  543.             self.__Error = T_ERROR_INCORRECT_STATE
  544.             return False
  545.    
  546.     def Terminate(self, DisableStateCheck = False):
  547.         self.__DebugPrint("Terminate(): In function")
  548.        
  549.         ## Don't merge with next condition due to clarity
  550.         if DisableStateCheck:
  551.             self.__MsgQueue.put_nowait((MESSAGE_TERMINATE, 0, 0))
  552.             self.__DebugPrint("Terminate(): Notice: message is sent")
  553.             self.__Error = T_SUCCESS
  554.             return True
  555.        
  556.         elif self.__State != TIMER_STATE_IDLE:
  557.             self.__MsgQueue.put_nowait((MESSAGE_TERMINATE, 0, 0))
  558.             self.__DebugPrint("Terminate(): Notice: message is sent")
  559.             self.__Error = T_SUCCESS
  560.             return True
  561.         else:
  562.             self.__DebugPrint(">> Terminate(): " + self.__OutputErrorState([TIMER_STATE_IDLE], Invert=True))
  563.             self.__Error = T_ERROR_INCORRECT_STATE
  564.             return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement