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