4 @todo Look into switching from POLL_TIME = min(F * 2^n, MAX) to POLL_TIME = min(CONST + F * 2^n, MAX)
5 @todo Look into supporting more states that have a different F and MAX
12 import util.go_utils as gobject_utils
13 import util.coroutines as coroutines
17 _moduleLogger = logging.getLogger("gvoice.state_machine")
20 def to_milliseconds(**kwd):
21 if "milliseconds" in kwd:
22 return kwd["milliseconds"]
23 elif "seconds" in kwd:
24 return kwd["seconds"] * 1000
25 elif "minutes" in kwd:
26 return kwd["minutes"] * 1000 * 60
28 return kwd["hours"] * 1000 * 60 * 60
29 raise KeyError("Unknown arg: %r" % kwd)
32 class NopStateStrategy(object):
37 def initialize_state(self):
40 def increment_state(self):
45 return UpdateStateMachine.INFINITE_PERIOD
48 class ConstantStateStrategy(object):
50 def __init__(self, timeout):
51 assert 0 < timeout or timeout == UpdateStateMachine.INFINITE_PERIOD
52 self._timeout = timeout
54 def initialize_state(self):
57 def increment_state(self):
65 class GeometricStateStrategy(object):
67 def __init__(self, init, min, max):
68 assert 0 < init and init < max and init != UpdateStateMachine.INFINITE_PERIOD
69 assert 0 < min and min != UpdateStateMachine.INFINITE_PERIOD
70 assert min < max or max == UpdateStateMachine.INFINITE_PERIOD
74 self._actualInit = init
77 def initialize_state(self):
78 self._current = self._min / 2
79 self._actualInit = self._init - self._min
81 def increment_state(self):
82 if self._max == UpdateStateMachine.INFINITE_PERIOD:
85 self._current = min(2 * self._current, self._max - self._init)
89 return self._actualInit + self._current
92 class StateMachine(object):
94 STATE_ACTIVE = 0, "active"
95 STATE_IDLE = 1, "idle"
99 raise NotImplementedError("Abstract")
102 raise NotImplementedError("Abstract")
105 raise NotImplementedError("Abstract")
107 def set_state(self, state):
108 raise NotImplementedError("Abstract")
112 raise NotImplementedError("Abstract")
115 class MasterStateMachine(StateMachine):
119 self._state = self.STATE_ACTIVE
121 def append_machine(self, machine):
122 self._machines.append(machine)
125 # Confirm we are all on the same page
126 for machine in self._machines:
127 machine.set_state(self._state)
128 for machine in self._machines:
132 for machine in self._machines:
136 for machine in self._machines:
139 def set_state(self, state):
141 for machine in self._machines:
142 machine.set_state(state)
149 class UpdateStateMachine(StateMachine):
150 # Making sure the it is initialized is finicky, be careful
156 def __init__(self, updateItems, name=""):
158 self._updateItems = updateItems
160 self._state = self.STATE_ACTIVE
161 self._timeoutId = None
163 self._strategies = {}
164 self._callback = coroutines.func_sink(
165 coroutines.expand_positional(
166 self._request_reset_timers
170 def set_state_strategy(self, state, strategy):
171 self._strategies[state] = strategy
174 assert self._timeoutId is None
175 for strategy in self._strategies.itervalues():
176 strategy.initialize_state()
177 self._timeoutId = gobject.idle_add(self._on_timeout)
178 _moduleLogger.info("%s Starting State Machine" % (self._name, ))
184 self._callback = None
186 def set_state(self, newState):
187 if self._state == newState:
189 oldState = self._state
190 _moduleLogger.info("%s Transitioning from %s to %s" % (self._name, oldState, newState))
192 self._state = newState
199 def reset_timers(self):
203 def request_reset_timers(self):
204 return self._callback
208 return self._strategies[self._state]
210 @gtk_toolbox.log_exception(_moduleLogger)
211 def _request_reset_timers(self, *args):
214 def _set_initial_period(self):
215 self._currentPeriod = self._INITIAL_ACTIVE_PERIOD / 2 # We will double it later
217 def _schedule_update(self):
218 assert self._timeoutId is None
219 self._strategy.increment_state()
220 nextTimeout = self._strategy.timeout
221 if nextTimeout != self.INFINITE_PERIOD:
222 self._timeoutId = gobject.timeout_add(nextTimeout, self._on_timeout)
223 _moduleLogger.info("%s Next update in %s ms" % (self._name, nextTimeout, ))
225 def _stop_update(self):
226 if self._timeoutId is None:
228 gobject.source_remove(self._timeoutId)
229 self._timeoutId = None
231 def _reset_timers(self):
232 if self._timeoutId is None:
233 return # not started yet
235 self._strategy.initialize_state()
236 self._schedule_update()
238 @gtk_toolbox.log_exception(_moduleLogger)
239 def _on_timeout(self):
240 _moduleLogger.debug("%s Update" % (self._name))
241 for item in self._updateItems:
243 item.update(force=True)
245 _moduleLogger.exception("Update failed for %r" % item)
246 self._timeoutId = None
247 self._schedule_update()
248 return False # do not continue