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