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