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