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