Adding a threshold where if a timeout goes above it, we just set it to infinite
[theonering] / src / gvoice / state_machine.py
index d26a57c..ba7ce8b 100644 (file)
@@ -1,10 +1,5 @@
 #!/usr/bin/env python
 
-"""
-@todo Look into switching from POLL_TIME = min(F * 2^n, MAX) to POLL_TIME = min(CONST + F * 2^n, MAX)
-@todo Look into supporting more states that have a different F and MAX
-"""
-
 import logging
 
 import gobject
@@ -29,6 +24,18 @@ def to_milliseconds(**kwd):
        raise KeyError("Unknown arg: %r" % kwd)
 
 
+def to_seconds(**kwd):
+       if "milliseconds" in kwd:
+               return kwd["milliseconds"] / 1000
+       elif "seconds" in kwd:
+               return kwd["seconds"]
+       elif "minutes" in kwd:
+               return kwd["minutes"] * 60
+       elif "hours" in kwd:
+               return kwd["hours"] * 60 * 60
+       raise KeyError("Unknown arg: %r" % kwd)
+
+
 class NopStateStrategy(object):
 
        def __init__(self):
@@ -65,16 +72,16 @@ class ConstantStateStrategy(object):
 class GeometricStateStrategy(object):
 
        def __init__(self, init, min, max):
-               assert 0 < init or init == UpdateStateMachine.INFINITE_PERIOD
-               assert 0 < min or min == UpdateStateMachine.INFINITE_PERIOD
+               assert 0 < init and init < max and init != UpdateStateMachine.INFINITE_PERIOD
+               assert 0 < min and min != UpdateStateMachine.INFINITE_PERIOD
                assert min < max or max == UpdateStateMachine.INFINITE_PERIOD
                self._min = min
                self._max = max
                self._init = init
-               self._current = min / 2
+               self._current = 0
 
        def initialize_state(self):
-               self._current = self._min / 2
+               self._current = self._min
 
        def increment_state(self):
                if self._max == UpdateStateMachine.INFINITE_PERIOD:
@@ -84,7 +91,8 @@ class GeometricStateStrategy(object):
 
        @property
        def timeout(self):
-               return self._init + self._current
+               timeout = self._init + self._current
+               return timeout
 
 
 class StateMachine(object):
@@ -148,11 +156,14 @@ class UpdateStateMachine(StateMachine):
        # Making sure the it is initialized is finicky, be careful
 
        INFINITE_PERIOD = -1
+       DEFAULT_MAX_TIMEOUT = to_seconds(hours=24)
 
        _IS_DAEMON = True
 
-       def __init__(self, updateItems):
+       def __init__(self, updateItems, name="", maxTime = DEFAULT_MAX_TIMEOUT):
+               self._name = name
                self._updateItems = updateItems
+               self._maxTime = maxTime
 
                self._state = self.STATE_ACTIVE
                self._timeoutId = None
@@ -171,13 +182,16 @@ class UpdateStateMachine(StateMachine):
                assert self._timeoutId is None
                for strategy in self._strategies.itervalues():
                        strategy.initialize_state()
-               self._timeoutId = gobject.idle_add(self._on_timeout)
+               if self._strategy.timeout != self.INFINITE_PERIOD:
+                       self._timeoutId = gobject.idle_add(self._on_timeout)
                _moduleLogger.info("%s Starting State Machine" % (self._name, ))
 
        def stop(self):
+               _moduleLogger.info("%s Stopping State Machine" % (self._name, ))
                self._stop_update()
 
        def close(self):
+               assert self._timeoutId is None
                self._callback = None
 
        def set_state(self, newState):
@@ -194,6 +208,7 @@ class UpdateStateMachine(StateMachine):
                return self._state
 
        def reset_timers(self):
+               _moduleLogger.info("%s Resetting State Machine" % (self._name, ))
                self._reset_timers()
 
        @property
@@ -204,25 +219,16 @@ class UpdateStateMachine(StateMachine):
        def _strategy(self):
                return self._strategies[self._state]
 
-       @property
-       def _name(self):
-               return "/".join(type(s).__name__ for s in self._updateItems)
-
-       @gobject_utils.async
        @gtk_toolbox.log_exception(_moduleLogger)
        def _request_reset_timers(self, *args):
                self._reset_timers()
 
-       def _set_initial_period(self):
-               self._currentPeriod = self._INITIAL_ACTIVE_PERIOD / 2 # We will double it later
-
-       def _schedule_update(self):
-               assert self._timeoutId is None
-               self._strategy.increment_state()
-               nextTimeout = self._strategy.timeout
-               if nextTimeout != self.INFINITE_PERIOD:
-                       self._timeoutId = gobject.timeout_add(nextTimeout, self._on_timeout)
-               _moduleLogger.info("%s Next update in %s ms" % (self._name, nextTimeout, ))
+       def _reset_timers(self):
+               if self._timeoutId is None:
+                       return # not started yet
+               self._stop_update()
+               self._strategy.initialize_state()
+               self._schedule_update()
 
        def _stop_update(self):
                if self._timeoutId is None:
@@ -230,20 +236,21 @@ class UpdateStateMachine(StateMachine):
                gobject.source_remove(self._timeoutId)
                self._timeoutId = None
 
-       def _reset_timers(self):
-               if self._timeoutId is None:
-                       return # not started yet
-               self._stop_update()
-               self._strategy.initialize_state()
-               self._schedule_update()
+       def _schedule_update(self):
+               assert self._timeoutId is None
+               self._strategy.increment_state()
+               nextTimeout = self._strategy.timeout
+               if nextTimeout != self.INFINITE_PERIOD and nextTimeout < self._maxTime:
+                       self._timeoutId = gobject_utils.timeout_add_seconds(nextTimeout, self._on_timeout)
+               _moduleLogger.info("%s Next update in %s seconds" % (self._name, nextTimeout, ))
 
+       @gtk_toolbox.log_exception(_moduleLogger)
        def _on_timeout(self):
-               _moduleLogger.info("%s Update" % (self._name))
+               self._timeoutId = None
+               self._schedule_update()
                for item in self._updateItems:
                        try:
                                item.update(force=True)
                        except Exception:
                                _moduleLogger.exception("Update failed for %r" % item)
-               self._timeoutId = None
-               self._schedule_update()
                return False # do not continue