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