about layout fix
[enigma2.git] / timer.py
1 import bisect
2 import time
3 import calendar
4 from enigma import *
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):
34                 print "ProcessRepeated"
35                 if (self.repeated != 0):
36                         now = int(time.time()) + 1
37
38                         #to avoid problems with daylight saving, we need to calculate with localtime, in struct_time representation
39                         localbegin = time.localtime(self.begin)
40                         localend = time.localtime(self.end)
41                         localnow = time.localtime(now)
42
43                         print time.strftime("%c", localbegin)
44                         print time.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 time.strftime("%c", localnow)
57                         while ((day[localbegin.tm_wday] != 0) or ((day[localbegin.tm_wday] == 0) and localend < localnow)):
58                                 print time.strftime("%c", localbegin)
59                                 print time.strftime("%c", localend)
60                                 #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
61                                 localbegin = time.gmtime(calendar.timegm(localbegin) + 86400)
62                                 localend = time.gmtime(calendar.timegm(localend) + 86400)
63
64                         #we now have a struct_time representation of begin and end in localtime, but we have to calculate back to (gmt) seconds since epoch
65                         self.begin = int(time.mktime(localbegin))
66                         self.end = int(time.mktime(localend)) + 1
67
68                         print "ProcessRepeated result"
69                         print time.strftime("%c", time.localtime(self.begin))
70                         print time.strftime("%c", time.localtime(self.end))
71
72                         self.timeChanged()
73
74         def __lt__(self, o):
75                 return self.getNextActivation() < o.getNextActivation()
76         
77         # must be overridden
78         def activate(self):
79                 pass
80                 
81         # can be overridden
82         def timeChanged(self):
83                 pass
84
85         # check if a timer entry must be skipped
86         def shouldSkip(self):
87                 return self.end <= time.time() and self.state == TimerEntry.StateWaiting
88
89         def abort(self):
90                 self.end = time.time()
91                 
92                 # in case timer has not yet started, but gets aborted (so it's preparing),
93                 # set begin to now.
94                 if self.begin > self.end:
95                         self.begin = self.end
96
97                 self.cancelled = True
98         
99         # must be overridden!
100         def getNextActivation():
101                 pass
102
103         def disable(self):
104                 self.disabled = True
105         
106         def enable(self):
107                 self.disabled = False
108
109 class Timer:
110         # the time between "polls". We do this because
111         # we want to account for time jumps etc.
112         # of course if they occur <100s before starting,
113         # it's not good. thus, you have to repoll when
114         # you change the time.
115         #
116         # this is just in case. We don't want the timer 
117         # hanging. we use this "edge-triggered-polling-scheme"
118         # anyway, so why don't make it a bit more fool-proof?
119         MaxWaitTime = 100
120
121         def __init__(self):
122                 self.timer_list = [ ]
123                 self.processed_timers = [ ]
124                 
125                 self.timer = eTimer()
126                 self.timer.timeout.get().append(self.calcNextActivation)
127                 self.lastActivation = time.time()
128                 
129                 self.calcNextActivation()
130                 self.on_state_change = [ ]
131         
132         def stateChanged(self, entry):
133                 for f in self.on_state_change:
134                         f(entry)
135                         
136         def getNextRecordingTime(self):
137                 if len(self.timer_list) > 0:
138                         return self.timer_list[0].begin
139                 return -1
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                         bisect.insort(self.processed_timers, entry)
156                         entry.state = TimerEntry.StateEnded
157                 else:
158                         bisect.insort(self.timer_list, entry)
159                         if not noRecalc:
160                                 self.calcNextActivation()
161         
162         def setNextActivation(self, when):
163                 delay = int((when - time.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.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.time()
181         
182                 min = int(time.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                         bisect.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                                 bisect.insort(self.processed_timers, w)
231                 
232                 self.stateChanged(w)
233
234         def processActivation(self):
235                 print "It's now ", time.strftime("%c", time.localtime(time.time()))
236                 t = int(time.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])