move function to better place
[openblackhole/openblackhole-enigma2.git] / timer.py
1 from bisect import insort
2 from time import strftime, time, localtime, mktime
3 from enigma import eTimer
4 import datetime
5
6 class TimerEntry:
7         StateWaiting  = 0
8         StatePrepared = 1
9         StateRunning  = 2
10         StateEnded    = 3
11         
12         def __init__(self, begin, end):
13                 self.begin = begin
14                 self.prepare_time = 20
15                 self.end = end
16                 self.state = 0
17                 self.resetRepeated()
18                 #begindate = localtime(self.begin)
19                 #newdate = datetime.datetime(begindate.tm_year, begindate.tm_mon, begindate.tm_mday 0, 0, 0);
20                 self.repeatedbegindate = begin
21                 self.backoff = 0
22                 
23                 self.disabled = False
24
25         def resetState(self):
26                 self.state = self.StateWaiting
27                 self.cancelled = False
28                 self.first_try_prepare = True
29                 self.timeChanged()
30
31         def resetRepeated(self):
32                 self.repeated = int(0)
33
34         def setRepeated(self, day):
35                 self.repeated |= (2 ** day)
36                 print "Repeated: " + str(self.repeated)
37                 
38         def isRunning(self):
39                 return self.state == self.StateRunning
40                 
41         def addOneDay(self, timedatestruct):
42                 oldHour = timedatestruct.tm_hour
43                 newdate =  (datetime.datetime(timedatestruct.tm_year, timedatestruct.tm_mon, timedatestruct.tm_mday, timedatestruct.tm_hour, timedatestruct.tm_min, timedatestruct.tm_sec) + datetime.timedelta(days=1)).timetuple()
44                 if localtime(mktime(newdate)).tm_hour != oldHour:
45                         return (datetime.datetime(timedatestruct.tm_year, timedatestruct.tm_mon, timedatestruct.tm_mday, timedatestruct.tm_hour, timedatestruct.tm_min, timedatestruct.tm_sec) + datetime.timedelta(days=2)).timetuple()                        
46                 return newdate
47                 
48         # update self.begin and self.end according to the self.repeated-flags
49         def processRepeated(self, findRunningEvent = True):
50                 print "ProcessRepeated"
51                 if (self.repeated != 0):
52                         now = int(time()) + 1
53
54                         #to avoid problems with daylight saving, we need to calculate with localtime, in struct_time representation
55                         localrepeatedbegindate = localtime(self.repeatedbegindate)
56                         localbegin = localtime(self.begin)
57                         localend = localtime(self.end)
58                         localnow = localtime(now)
59
60                         print "localrepeatedbegindate:", strftime("%c", localrepeatedbegindate)
61                         print "localbegin:", strftime("%c", localbegin)
62                         print "localend:", strftime("%c", localend)
63                         print "localnow:", strftime("%c", localnow)
64
65                         day = []
66                         flags = self.repeated
67                         for x in range(0, 7):
68                                 if (flags & 1 == 1):
69                                         day.append(0)
70                                         print "Day: " + str(x)
71                                 else:
72                                         day.append(1)
73                                 flags = flags >> 1
74
75                         # if day is NOT in the list of repeated days
76                         # OR if the day IS in the list of the repeated days, check, if event is currently running... then if findRunningEvent is false, go to the next event
77                         while ((day[localbegin.tm_wday] != 0) or (mktime(localrepeatedbegindate) > mktime(localbegin))  or
78                                 ((day[localbegin.tm_wday] == 0) and ((findRunningEvent and localend < localnow) or ((not findRunningEvent) and localbegin < localnow)))):
79                                 localbegin = self.addOneDay(localbegin)
80                                 localend = self.addOneDay(localend)
81                                 print "localbegin after addOneDay:", strftime("%c", localbegin)
82                                 print "localend after addOneDay:", strftime("%c", localend)
83                                 
84                         #we now have a struct_time representation of begin and end in localtime, but we have to calculate back to (gmt) seconds since epoch
85                         self.begin = int(mktime(localbegin))
86                         self.end = int(mktime(localend))
87                         if self.begin == self.end:
88                                 self.end += 1
89
90                         print "ProcessRepeated result"
91                         print strftime("%c", localtime(self.begin))
92                         print strftime("%c", localtime(self.end))
93
94                         self.timeChanged()
95
96         def __lt__(self, o):
97                 return self.getNextActivation() < o.getNextActivation()
98         
99         # must be overridden
100         def activate(self):
101                 pass
102                 
103         # can be overridden
104         def timeChanged(self):
105                 pass
106
107         # check if a timer entry must be skipped
108         def shouldSkip(self):
109                 return self.end <= time() and self.state == TimerEntry.StateWaiting
110
111         def abort(self):
112                 self.end = time()
113                 
114                 # in case timer has not yet started, but gets aborted (so it's preparing),
115                 # set begin to now.
116                 if self.begin > self.end:
117                         self.begin = self.end
118
119                 self.cancelled = True
120         
121         # must be overridden!
122         def getNextActivation():
123                 pass
124
125         def disable(self):
126                 self.disabled = True
127         
128         def enable(self):
129                 self.disabled = False
130
131 class Timer:
132         # the time between "polls". We do this because
133         # we want to account for time jumps etc.
134         # of course if they occur <100s before starting,
135         # it's not good. thus, you have to repoll when
136         # you change the time.
137         #
138         # this is just in case. We don't want the timer 
139         # hanging. we use this "edge-triggered-polling-scheme"
140         # anyway, so why don't make it a bit more fool-proof?
141         MaxWaitTime = 100
142
143         def __init__(self):
144                 self.timer_list = [ ]
145                 self.processed_timers = [ ]
146                 
147                 self.timer = eTimer()
148                 self.timer.callback.append(self.calcNextActivation)
149                 self.lastActivation = time()
150                 
151                 self.calcNextActivation()
152                 self.on_state_change = [ ]
153
154         def stateChanged(self, entry):
155                 for f in self.on_state_change:
156                         f(entry)
157
158         def cleanup(self):
159                 self.processed_timers = [entry for entry in self.processed_timers if entry.disabled]
160         
161         def addTimerEntry(self, entry, noRecalc=0):
162                 entry.processRepeated()
163
164                 # when the timer has not yet started, and is already passed,
165                 # don't go trough waiting/running/end-states, but sort it
166                 # right into the processedTimers.
167                 if entry.shouldSkip() or entry.state == TimerEntry.StateEnded or (entry.state == TimerEntry.StateWaiting and entry.disabled):
168                         print "already passed, skipping"
169                         print "shouldSkip:", entry.shouldSkip()
170                         print "state == ended", entry.state == TimerEntry.StateEnded
171                         print "waiting && disabled:", (entry.state == TimerEntry.StateWaiting and entry.disabled)
172                         insort(self.processed_timers, entry)
173                         entry.state = TimerEntry.StateEnded
174                 else:
175                         insort(self.timer_list, entry)
176                         if not noRecalc:
177                                 self.calcNextActivation()
178         
179         def setNextActivation(self, when):
180                 delay = int((when - time()) * 1000)
181                 print "[timer.py] next activation: %d (in %d ms)" % (when, delay)
182                 
183                 self.timer.start(delay, 1)
184                 self.next = when
185
186         def calcNextActivation(self):
187                 if self.lastActivation > time():
188                         print "[timer.py] timewarp - re-evaluating all processed timers."
189                         tl = self.processed_timers
190                         self.processed_timers = [ ]
191                         for x in tl:
192                                 # simulate a "waiting" state to give them a chance to re-occure
193                                 x.resetState()
194                                 self.addTimerEntry(x, noRecalc=1)
195                 
196                 self.processActivation()
197                 self.lastActivation = time()
198         
199                 min = int(time()) + self.MaxWaitTime
200                 
201                 # calculate next activation point
202                 if len(self.timer_list):
203                         w = self.timer_list[0].getNextActivation()
204                         if w < min:
205                                 min = w
206                         else:
207                                 print "next real activation is", strftime("%c", localtime(w))
208                 
209                 self.setNextActivation(min)
210         
211         def timeChanged(self, timer):
212                 print "time changed"
213                 timer.timeChanged()
214                 if timer.state == TimerEntry.StateEnded:
215                         self.processed_timers.remove(timer)
216                 else:
217                         self.timer_list.remove(timer)
218
219                 # give the timer a chance to re-enqueue
220                 if timer.state == TimerEntry.StateEnded:
221                         timer.state = TimerEntry.StateWaiting
222                 self.addTimerEntry(timer)
223         
224         def doActivate(self, w):
225                 self.timer_list.remove(w)
226                 
227                 # when activating a timer which has already passed,
228                 # simply abort the timer. don't run trough all the stages.
229                 if w.shouldSkip():
230                         w.state = TimerEntry.StateEnded
231                 else:
232                         # when active returns true, this means "accepted".
233                         # otherwise, the current state is kept.
234                         # the timer entry itself will fix up the delay then.
235                         if w.activate():
236                                 w.state += 1
237
238                 # did this timer reached the last state?
239                 if w.state < TimerEntry.StateEnded:
240                         # no, sort it into active list
241                         insort(self.timer_list, w)
242                 else:
243                         # yes. Process repeated, and re-add.
244                         if w.repeated:
245                                 w.processRepeated()
246                                 w.state = TimerEntry.StateWaiting
247                                 self.addTimerEntry(w)
248                         else:
249                                 insort(self.processed_timers, w)
250                 
251                 self.stateChanged(w)
252
253         def processActivation(self):
254                 print "It's now ", strftime("%c", localtime(time()))
255                 t = int(time()) + 1
256                 
257                 # we keep on processing the first entry until it goes into the future.
258                 while len(self.timer_list) and self.timer_list[0].getNextActivation() < t:
259                         self.doActivate(self.timer_list[0])