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