Revert "Advanced functions(edit/delete/disable) repeated timers in EPG list"
[openblackhole/openblackhole-enigma2.git] / timer.py
1 from bisect import insort
2 from time import strftime, time, localtime, mktime
3 from enigma import eTimer
4 import datetime
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                 #begindate = localtime(self.begin)
19                 #newdate = datetime.datetime(begindate.tm_year, begindate.tm_mon, begindate.tm_mday 0, 0, 0);
20                 self.repeatedbegindate = begin
21                 self.backoff = 0
22
23                 self.disabled = False
24
25         def resetState(self):
26                 self.state = self.StateWaiting
27                 self.cancelled = False
28                 self.first_try_prepare = True
29                 self.timeChanged()
30
31         def resetRepeated(self):
32                 self.repeated = int(0)
33
34         def setRepeated(self, day):
35                 self.repeated |= (2 ** day)
36
37         def isRunning(self):
38                 return self.state == self.StateRunning
39
40         def addOneDay(self, timedatestruct):
41                 oldHour = timedatestruct.tm_hour
42                 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()
43                 if localtime(mktime(newdate)).tm_hour != oldHour:
44                         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()
45                 return newdate
46
47         # update self.begin and self.end according to the self.repeated-flags
48         def processRepeated(self, findRunningEvent = True):
49                 if (self.repeated != 0):
50                         now = int(time()) + 1
51
52                         #to avoid problems with daylight saving, we need to calculate with localtime, in struct_time representation
53                         localrepeatedbegindate = localtime(self.repeatedbegindate)
54                         localbegin = localtime(self.begin)
55                         localend = localtime(self.end)
56                         localnow = localtime(now)
57
58                         day = []
59                         flags = self.repeated
60                         for x in (0, 1, 2, 3, 4, 5, 6):
61                                 if (flags & 1 == 1):
62                                         day.append(0)
63                                 else:
64                                         day.append(1)
65                                 flags = flags >> 1
66
67                         # if day is NOT in the list of repeated days
68                         # OR if the day IS in the list of the repeated days, check, if event is currently running... then if findRunningEvent is false, go to the next event
69                         while ((day[localbegin.tm_wday] != 0) or (mktime(localrepeatedbegindate) > mktime(localbegin))  or
70                                 ((day[localbegin.tm_wday] == 0) and ((findRunningEvent and localend < localnow) or ((not findRunningEvent) and localbegin < localnow)))):
71                                 localbegin = self.addOneDay(localbegin)
72                                 localend = self.addOneDay(localend)
73
74                         #we now have a struct_time representation of begin and end in localtime, but we have to calculate back to (gmt) seconds since epoch
75                         self.begin = int(mktime(localbegin))
76                         self.end = int(mktime(localend))
77                         if self.begin == self.end:
78                                 self.end += 1
79
80                         self.timeChanged()
81
82         def __lt__(self, o):
83                 return self.getNextActivation() < o.getNextActivation()
84
85         # must be overridden
86         def activate(self):
87                 pass
88
89         # can be overridden
90         def timeChanged(self):
91                 pass
92
93         # check if a timer entry must be skipped
94         def shouldSkip(self):
95                 return self.end <= time() and self.state == TimerEntry.StateWaiting
96
97         def abort(self):
98                 self.end = time()
99
100                 # in case timer has not yet started, but gets aborted (so it's preparing),
101                 # set begin to now.
102                 if self.begin > self.end:
103                         self.begin = self.end
104
105                 self.cancelled = True
106
107         # must be overridden!
108         def getNextActivation():
109                 pass
110
111         def disable(self):
112                 self.disabled = True
113
114         def enable(self):
115                 self.disabled = False
116
117 class Timer:
118         # the time between "polls". We do this because
119         # we want to account for time jumps etc.
120         # of course if they occur <100s before starting,
121         # it's not good. thus, you have to repoll when
122         # you change the time.
123         #
124         # this is just in case. We don't want the timer
125         # hanging. we use this "edge-triggered-polling-scheme"
126         # anyway, so why don't make it a bit more fool-proof?
127         MaxWaitTime = 100
128
129         def __init__(self):
130                 self.timer_list = [ ]
131                 self.processed_timers = [ ]
132
133                 self.timer = eTimer()
134                 self.timer.callback.append(self.calcNextActivation)
135                 self.lastActivation = time()
136
137                 self.calcNextActivation()
138                 self.on_state_change = [ ]
139
140         def stateChanged(self, entry):
141                 for f in self.on_state_change:
142                         f(entry)
143
144         def cleanup(self):
145                 self.processed_timers = [entry for entry in self.processed_timers if entry.disabled]
146
147         def cleanupDaily(self, days):
148                 limit = time() - (days * 3600 * 24)
149                 self.processed_timers = [entry for entry in self.processed_timers if (entry.disabled and entry.repeated) or (entry.end and (entry.end > limit))]
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                         insort(self.processed_timers, entry)
159                         entry.state = TimerEntry.StateEnded
160                 else:
161                         insort(self.timer_list, entry)
162                         if not noRecalc:
163                                 self.calcNextActivation()
164
165 # small piece of example code to understand how to use record simulation
166 #               if NavigationInstance.instance:
167 #                       lst = [ ]
168 #                       cnt = 0
169 #                       for timer in self.timer_list:
170 #                               print "timer", cnt
171 #                               cnt += 1
172 #                               if timer.state == 0: #waiting
173 #                                       lst.append(NavigationInstance.instance.recordService(timer.service_ref))
174 #                               else:
175 #                                       print "STATE: ", timer.state
176 #
177 #                       for rec in lst:
178 #                               if rec.start(True): #simulate
179 #                                       print "FAILED!!!!!!!!!!!!"
180 #                               else:
181 #                                       print "OK!!!!!!!!!!!!!!"
182 #                               NavigationInstance.instance.stopRecordService(rec)
183 #               else:
184 #                       print "no NAV"
185
186         def setNextActivation(self, now, when):
187                 delay = int((when - now) * 1000)
188                 self.timer.start(delay, 1)
189                 self.next = when
190
191         def calcNextActivation(self):
192                 now = time()
193                 if self.lastActivation > now:
194                         print "[timer.py] timewarp - re-evaluating all processed timers."
195                         tl = self.processed_timers
196                         self.processed_timers = [ ]
197                         for x in tl:
198                                 # simulate a "waiting" state to give them a chance to re-occure
199                                 x.resetState()
200                                 self.addTimerEntry(x, noRecalc=1)
201
202                 self.processActivation()
203                 self.lastActivation = now
204
205                 min = int(now) + self.MaxWaitTime
206
207                 # calculate next activation point
208                 if self.timer_list:
209                         w = self.timer_list[0].getNextActivation()
210                         if w < min:
211                                 min = w
212
213                 if int(now) < 1072224000 and min > now + 5:
214                         # system time has not yet been set (before 01.01.2004), keep a short poll interval
215                         min = now + 5
216
217                 self.setNextActivation(now, min)
218
219         def timeChanged(self, timer):
220                 print "time changed"
221                 timer.timeChanged()
222                 if timer.state == TimerEntry.StateEnded:
223                         self.processed_timers.remove(timer)
224                 else:
225                         try:
226                                 self.timer_list.remove(timer)
227                         except:
228                                 print "[timer] Failed to remove, not in list"
229                                 return
230                 # give the timer a chance to re-enqueue
231                 if timer.state == TimerEntry.StateEnded:
232                         timer.state = TimerEntry.StateWaiting
233                 self.addTimerEntry(timer)
234
235         def doActivate(self, w):
236                 self.timer_list.remove(w)
237
238                 # when activating a timer which has already passed,
239                 # simply abort the timer. don't run trough all the stages.
240                 if w.shouldSkip():
241                         w.state = TimerEntry.StateEnded
242                 else:
243                         # when active returns true, this means "accepted".
244                         # otherwise, the current state is kept.
245                         # the timer entry itself will fix up the delay then.
246                         if w.activate():
247                                 w.state += 1
248
249                 # did this timer reached the last state?
250                 if w.state < TimerEntry.StateEnded:
251                         # no, sort it into active list
252                         insort(self.timer_list, w)
253                 else:
254                         # yes. Process repeated, and re-add.
255                         if w.repeated:
256                                 w.processRepeated()
257                                 w.state = TimerEntry.StateWaiting
258                                 self.addTimerEntry(w)
259                         else:
260                                 insort(self.processed_timers, w)
261
262                 self.stateChanged(w)
263
264         def processActivation(self):
265                 t = int(time()) + 1
266                 # we keep on processing the first entry until it goes into the future.
267                 while self.timer_list and self.timer_list[0].getNextActivation() < t:
268                         self.doActivate(self.timer_list[0])