6b0a58d8255b5c9550181a978613373deddf76c6
[theonering] / src / gvoice / state_machine.py
1 #!/usr/bin/env python
2
3 """
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
6 """
7
8 import logging
9
10 import gobject
11
12 import util.go_utils as gobject_utils
13 import util.coroutines as coroutines
14 import gtk_toolbox
15
16
17 _moduleLogger = logging.getLogger("gvoice.state_machine")
18
19
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
27         raise KeyError("Unknown arg: %r" % kwd)
28
29
30 class StateMachine(object):
31
32         STATE_ACTIVE = 0, "active"
33         STATE_IDLE = 1, "idle"
34         STATE_DND = 2, "dnd"
35
36         _ACTION_UPDATE = "update"
37         _ACTION_RESET = "reset"
38         _ACTION_STOP = "stop"
39
40         _INITIAL_ACTIVE_PERIOD = int(_to_milliseconds(seconds=5))
41         _FINAL_ACTIVE_PERIOD = int(_to_milliseconds(minutes=2))
42         _IDLE_PERIOD = int(_to_milliseconds(minutes=10))
43         _INFINITE_PERIOD = -1
44
45         _IS_DAEMON = True
46
47         def __init__(self, initItems, updateItems):
48                 self._initItems = initItems
49                 self._updateItems = updateItems
50
51                 self._state = self.STATE_ACTIVE
52                 self._timeoutId = None
53                 self._currentPeriod = self._INITIAL_ACTIVE_PERIOD
54                 self._set_initial_period()
55
56                 self._callback = coroutines.func_sink(
57                         coroutines.expand_positional(
58                                 self._request_reset_timers
59                         )
60                 )
61
62         def close(self):
63                 self._callback = None
64
65         @gobject_utils.async
66         @gtk_toolbox.log_exception(_moduleLogger)
67         def start(self):
68                 _moduleLogger.info("Starting State Machine")
69                 for item in self._initItems:
70                         try:
71                                 item.update()
72                         except Exception:
73                                 _moduleLogger.exception("Initial update failed for %r" % item)
74                 self._schedule_update()
75
76         def stop(self):
77                 _moduleLogger.info("Stopping an already stopped state machine")
78                 self._stop_update()
79
80         def set_state(self, newState):
81                 oldState = self._state
82                 _moduleLogger.info("Transitioning from %s to %s" % (oldState, newState))
83
84                 self._state = newState
85                 self.reset_timers()
86
87         def get_state(self):
88                 return self._state
89
90         def reset_timers(self):
91                 self._reset_timers()
92
93         @property
94         def request_reset_timers(self):
95                 return self._callback
96
97         @gobject_utils.async
98         @gtk_toolbox.log_exception(_moduleLogger)
99         def _request_reset_timers(self, *args):
100                 self.reset_timers()
101
102         def _set_initial_period(self):
103                 self._currentPeriod = self._INITIAL_ACTIVE_PERIOD / 2 # We will double it later
104
105         def _schedule_update(self):
106                 nextTimeout = self._calculate_step(self._state, self._currentPeriod)
107                 nextTimeout = int(nextTimeout)
108                 if nextTimeout != self._INFINITE_PERIOD:
109                         self._timeoutId = gobject.timeout_add(nextTimeout, self._on_timeout)
110                 _moduleLogger.info("Next update in %s ms" % (nextTimeout, ))
111                 self._currentPeriod = nextTimeout
112
113         def _stop_update(self):
114                 if self._timeoutId is None:
115                         return
116                 gobject.source_remove(self._timeoutId)
117                 self._timeoutId = None
118
119         def _reset_timers(self):
120                 self._stop_update()
121                 self._set_initial_period()
122                 self._schedule_update()
123
124         def _on_timeout(self):
125                 _moduleLogger.info("Update")
126                 for item in self._updateItems:
127                         try:
128                                 item.update(force=True)
129                         except Exception:
130                                 _moduleLogger.exception("Update failed for %r" % item)
131                 self._schedule_update()
132                 return False # do not continue
133
134         @classmethod
135         def _calculate_step(cls, state, period):
136                 if state == cls.STATE_ACTIVE:
137                         return min(period * 2, cls._FINAL_ACTIVE_PERIOD)
138                 elif state == cls.STATE_IDLE:
139                         return cls._IDLE_PERIOD
140                 elif state == cls.STATE_DND:
141                         return cls._INFINITE_PERIOD
142                 else:
143                         raise RuntimeError("Unknown state: %r" % (state, ))