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