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