[Elektro] each profile needs its own Nextday
[enigma2-plugins.git] / elektro / src / plugin.py
1 #
2 # Power Save Plugin by gutemine
3 # Rewritten by Morty (morty@gmx.net)
4 # Profiles, HDD, IP Mod by joergm6
5 #
6 # Deep standby will be called sleep. Normal standby will be named standby!
7 # All calculations are in the local timezone, or in the relative Timezone.
8 # In the relative timezone the day starts at "nextday". If it is before nextday the last day will be used.
9 #
10 #
11
12
13 #from enigma import *
14 from __init__ import _
15
16 from Screens.InfoBarGenerics import *
17 # from RecordTimer import *
18
19
20 import calendar 
21 #################
22
23 # Plugin
24 from Plugins.Plugin import PluginDescriptor
25
26 # GUI (Screens)
27 from Screens.Screen import Screen
28 from Components.ConfigList import ConfigListScreen
29 from Screens.MessageBox import MessageBox
30 from Screens.Console import Console
31 from Screens import Standby 
32
33 # GUI (Summary)
34 # from Screens.Setup import SetupSummary
35
36 # GUI (Components)
37 from Components.ActionMap import ActionMap
38 from Components.Button import Button
39 from Components.Language import language
40 from Components.Harddisk import harddiskmanager
41 from Components.Sources.StaticText import StaticText
42
43 # Configuration
44 from Components.config import getConfigListEntry, ConfigEnableDisable, \
45         ConfigYesNo, ConfigText, ConfigClock, ConfigNumber, ConfigSelection, \
46         config, ConfigSubsection, ConfigSubList, ConfigSubDict, ConfigIP
47
48 # Startup/shutdown notification
49 from Tools import Notifications
50
51 import ping
52 import os
53 # Timer, etc
54
55 #import time
56 from time import localtime, asctime, time, gmtime
57 # import datetime
58 # import codecs
59
60
61 # Enigma system functions
62 from enigma import quitMainloop, eTimer
63
64
65 # import Wakeup?!
66 from Tools.DreamboxHardware import getFPWasTimerWakeup
67
68 ###############################################################################
69
70 # Globals
71 pluginPrintname = "[Elektro]"
72 debug = False # If set True, plugin will print some additional status info to track logic flow
73 session = None
74 ElektroWakeUpTime = -1
75 elektro_pluginversion = "3.4.4a"
76 elektro_readme = "/usr/lib/enigma2/python/Plugins/Extensions/Elektro/readme.txt"
77 elektro_readme_de  = "/usr/lib/enigma2/python/Plugins/Extensions/Elektro/readme-de.txt"
78 elektrostarttime = 60 
79 elektrosleeptime = 5
80 elektroShutdownThreshold = 60 * 20
81 ###############################################################################
82
83 #Configuration
84 if debug:
85         print pluginPrintname, "Setting config defaults"
86 config.plugins.elektro = ConfigSubsection()
87 config.plugins.elektro.nextday = ConfigClock(default = ((6 * 60 + 0) * 60) )
88 config.plugins.elektro.nextday2 = ConfigClock(default = ((6 * 60 + 0) * 60) )
89 config.plugins.elektro.profile = ConfigSelection(choices = [("1", "Profile 1"), ("2", "Profile 2")], default = "1")
90 config.plugins.elektro.profileShift =  ConfigYesNo(default = False)
91
92 config.plugins.elektro.sleep = ConfigSubDict()
93 for i in range(7):
94         config.plugins.elektro.sleep[i] = ConfigClock(default = ((1 * 60 + 0) * 60) )
95
96 config.plugins.elektro.wakeup = ConfigSubDict()
97 for i in range(7):
98         config.plugins.elektro.wakeup[i] = ConfigClock(default = ((9 * 60 + 0) * 60) )
99
100 config.plugins.elektro.sleep2 = ConfigSubDict()
101 for i in range(7):
102         config.plugins.elektro.sleep2[i] = ConfigClock(default = ((1 * 60 + 0) * 60) )
103
104 config.plugins.elektro.wakeup2 = ConfigSubDict()
105 for i in range(7):
106         config.plugins.elektro.wakeup2[i] = ConfigClock(default = ((9 * 60 + 0) * 60) )
107
108 config.plugins.elektro.ip = ConfigSubDict()
109 for i in range(10):
110         config.plugins.elektro.ip[i] = ConfigIP(default = [0, 0, 0, 0])
111
112 config.plugins.elektro.name = ConfigText(default = _("Elektro Power Save"), fixed_size = False, visible_width = 20)
113 config.plugins.elektro.description = ConfigText(default = _("Automatically shut down to deep standby"), fixed_size = False, visible_width = 80)
114 config.plugins.elektro.menu = ConfigSelection(default = "plugin", choices = [("plugin", _("Plugin menu")), ("extensions", _("Extensions menu"))])
115 config.plugins.elektro.enable = ConfigEnableDisable(default = False)
116 config.plugins.elektro.standbyOnBoot = ConfigYesNo(default = False)
117 config.plugins.elektro.standbyOnManualBoot = ConfigYesNo(default = True)
118 config.plugins.elektro.standbyOnBootTimeout = ConfigNumber(default = 60)
119 config.plugins.elektro.nextwakeup = ConfigNumber(default = 0)
120 config.plugins.elektro.force = ConfigYesNo(default = False)
121 config.plugins.elektro.dontwakeup = ConfigEnableDisable(default = False)
122 config.plugins.elektro.holiday =  ConfigEnableDisable(default = False)
123 config.plugins.elektro.hddsleep =  ConfigYesNo(default = False)
124 config.plugins.elektro.IPenable =  ConfigYesNo(default = False)
125
126
127
128 weekdays = [
129         _("Monday"),
130         _("Tuesday"),
131         _("Wednesday"),
132         _("Thursday"),
133         _("Friday"),
134         _("Saturday"),
135         _("Sunday"),
136         ]
137
138
139 #global ElektroWakeUpTime
140 ElektroWakeUpTime = -1
141
142 def autostart(reason, **kwargs):
143         global session  
144         if reason == 0 and kwargs.has_key("session"):
145                 session = kwargs["session"]
146                 session.open(DoElektro)
147
148 def getNextWakeup():
149         global ElektroWakeUpTime
150         
151         #it might happen, that session does not exist. I don't know why. :-(
152         if session is None:
153                 return ElektroWakeUpTime;
154         
155         nextTimer = session.nav.RecordTimer.getNextRecordingTime()
156         print pluginPrintname, "Now:", strftime("%a:%H:%M:%S",  gmtime(time()))
157         if (nextTimer < 1) or (nextTimer > ElektroWakeUpTime):
158                 print pluginPrintname, "Will wake up", strftime("%a:%H:%M:%S",  gmtime(ElektroWakeUpTime))
159                 return ElektroWakeUpTime
160         
161         #We have to make sure, that the Box will wake up because of us
162         # and not because of the timer
163         print pluginPrintname, "Will wake up due to the next timer", strftime("%a:%H:%M:%S",  gmtime(nextTimer))
164         return nextTimer - 1
165         
166 def Plugins(**kwargs):
167         if debug:
168                 print pluginPrintname, "Setting entry points"
169         list = [
170                 PluginDescriptor(
171                         name = config.plugins.elektro.name.value, 
172                         description = config.plugins.elektro.description.value + " "  + _("Ver.") + " " + elektro_pluginversion, 
173                         where = [
174                                 PluginDescriptor.WHERE_SESSIONSTART, 
175                                 PluginDescriptor.WHERE_AUTOSTART
176                         ], 
177                         fnc = autostart, 
178                         wakeupfnc = getNextWakeup)
179                 ]
180         if config.plugins.elektro.menu.value == "plugin":
181                 list.append (PluginDescriptor(
182                         name = config.plugins.elektro.name.value, 
183                         description = config.plugins.elektro.description.value + " "  + _("Ver.") + " " + elektro_pluginversion, 
184                         where = PluginDescriptor.WHERE_PLUGINMENU, 
185                         icon = "elektro.png", 
186                         fnc=main)
187                 )
188         else:
189                 list.append (PluginDescriptor(
190                         name = config.plugins.elektro.name.value, 
191                         description = config.plugins.elektro.description.value + " "  + _("Ver.") + " " + elektro_pluginversion, 
192                         where = PluginDescriptor.WHERE_EXTENSIONSMENU, 
193                         fnc=main)
194                 )               
195         
196         return list
197
198         
199 def main(session,**kwargs):
200         try:    
201                 session.open(Elektro)
202         except:
203                 print pluginPrintname, "Pluginexecution failed"
204
205 class ElektroProfile(ConfigListScreen,Screen):
206         skin = """
207                         <screen position="center,center" size="600,400" title="Elektro Power Save Profile Times" >
208                         <widget name="config" position="0,0" size="600,360" scrollbarMode="showOnDemand" />
209                         
210                         <widget name="key_red" position="0,360" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/> 
211                         <widget name="key_green" position="140,360" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/> 
212                         
213                         <ePixmap name="red"    position="0,360"   zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
214                         <ePixmap name="green"  position="140,360" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
215                 </screen>"""
216                 
217         def __init__(self, session, args = 0):
218                 self.session = session
219                 Screen.__init__(self, session)
220                 
221                 self.list = []
222
223                 for i in range(7):
224                         self.list.append(getConfigListEntry(" 1. " + weekdays[i] + ": "  + _("Wakeup"), config.plugins.elektro.wakeup[i]))
225                         self.list.append(getConfigListEntry(" 1. " + weekdays[i] + ": "  + _("Sleep"), config.plugins.elektro.sleep[i]))
226                 self.list.append(getConfigListEntry(" 1. " + _("Next day starts at"), config.plugins.elektro.nextday,
227                         _("If the box is supposed to enter deep standby e.g. monday night at 1 AM, it actually is already tuesday. To enable this anyway, differing next day start time can be specified here.")))
228                 for i in range(7):
229                         self.list.append(getConfigListEntry(" 2. " + weekdays[i] + ": "  + _("Wakeup"), config.plugins.elektro.wakeup2[i]))
230                         self.list.append(getConfigListEntry(" 2. " + weekdays[i] + ": "  + _("Sleep"), config.plugins.elektro.sleep2[i]))
231                 self.list.append(getConfigListEntry(" 2. " + _("Next day starts at"), config.plugins.elektro.nextday2,
232                         _("If the box is supposed to enter deep standby e.g. monday night at 1 AM, it actually is already tuesday. To enable this anyway, differing next day start time can be specified here.")))
233                         
234                 ConfigListScreen.__init__(self, self.list)
235                 
236                 self["key_red"] = Button(_("Cancel"))
237                 self["key_green"] = Button(_("Ok"))
238                 self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
239                 {
240                         "red": self.cancel,
241                         "green": self.save,
242                         "save": self.save,
243                         "cancel": self.cancel,
244                         "ok": self.save,
245                 }, -2)
246         
247         def save(self):
248                 #print "saving"
249                 for x in self["config"].list:
250                         x[1].save()
251                 self.close(False,self.session)
252
253         def cancel(self):
254                 #print "cancel"
255                 for x in self["config"].list:
256                         x[1].cancel()
257                 self.close(False,self.session)
258
259 class ElektroIP(ConfigListScreen,Screen):
260         skin = """
261                         <screen position="center,center" size="600,400" title="Elektro Power Save IP Addresses to wait" >
262                         <widget name="config" position="0,0" size="600,360" scrollbarMode="showOnDemand" />
263                         
264                         <widget name="key_red" position="0,360" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/> 
265                         <widget name="key_green" position="140,360" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/> 
266                         
267                         <ePixmap name="red"    position="0,360"   zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
268                         <ePixmap name="green"  position="140,360" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
269                 </screen>"""
270                 
271         def __init__(self, session, args = 0):
272                 self.session = session
273                 Screen.__init__(self, session)
274                 
275                 self.list = []
276
277                 for i in range(10):
278                         self.list.append(getConfigListEntry(_("%d. IP Address") % i , config.plugins.elektro.ip[i]))
279                         
280                 ConfigListScreen.__init__(self, self.list)
281                 
282                 self["key_red"] = Button(_("Cancel"))
283                 self["key_green"] = Button(_("Ok"))
284                 self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
285                 {
286                         "red": self.cancel,
287                         "green": self.save,
288                         "save": self.save,
289                         "cancel": self.cancel,
290                         "ok": self.save,
291                 }, -2)
292         
293         def save(self):
294                 #print "saving"
295                 for x in self["config"].list:
296                         x[1].save()
297                 self.close(False,self.session)
298
299         def cancel(self):
300                 #print "cancel"
301                 for x in self["config"].list:
302                         x[1].cancel()
303                 self.close(False,self.session)
304
305 class Elektro(ConfigListScreen,Screen):
306         skin = """
307                 <screen name ="Elektro" position="center,center" size="630,480" title="Elektro Power Save" >
308                         <widget name="key_red" position="4,5" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/> 
309                         <widget name="key_green" position="165,5" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/> 
310                         <widget name="key_yellow" position="325,5" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/>
311                         <widget name="key_blue" position="485,5" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;18" transparent="1"/>
312                         
313                         <ePixmap name="red"    position="5,5"   zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
314                         <ePixmap name="green"  position="165,5" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
315                         <ePixmap name="yellow" position="325,5" zPosition="2" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" /> 
316                         <ePixmap name="blue"   position="485,5" zPosition="2" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" /> 
317                         
318                         <widget name="config" position="5,50" size="620,275" scrollbarMode="showOnDemand" />            
319                          
320                         <ePixmap pixmap="skin_default/div-h.png" position="0,330" zPosition="1" size="630,2" />
321                         <widget source="help" render="Label" position="5,335" size="620,153" font="Regular;21" />                                       
322                 </screen>""" 
323                                         
324                 
325         def __init__(self, session, args = 0):
326                 self.session = session
327                 Screen.__init__(self, session)
328                 if debug:
329                         print pluginPrintname, "Displays config screen"                 
330
331                 self.onChangedEntry = []
332                 
333                 self.list = [   
334                         getConfigListEntry(_("Active Time Profile"), config.plugins.elektro.profile,
335                                 _("The active Time Profile is (1 or 2).")),
336                         getConfigListEntry(_("Enable Elektro Power Save"),config.plugins.elektro.enable,
337                                 _("Unless this is enabled, this plugin won't run automatically.")),                                                     
338                         getConfigListEntry(_("Use both profiles alternately"), config.plugins.elektro.profileShift,
339                                 _("Both profiles are used alternately. When shutting down the other profile is enabled. This allows two time cycles per day. Do not overlap the times.")),
340                         getConfigListEntry(_("Standby on boot"), config.plugins.elektro.standbyOnBoot,
341                                 _("Puts the box in standby mode after boot.")),
342                         getConfigListEntry(_("Standby on manual boot"), config.plugins.elektro.standbyOnManualBoot,
343                                 _("Whether to put the box in standby when booted manually. On manual boot the box will not go to standby before the next deep standby interval starts, even if this option is set. This option is only active if 'Standby on boot' option is set, too.")),
344                         getConfigListEntry(_("Standby on boot screen timeout"), config.plugins.elektro.standbyOnBootTimeout,
345                                 _("Specify how long to show the standby query on boot screen. This value can be set to ensure the box does not shut down to deep standby again too fast when in standby mode.")),
346                         getConfigListEntry(_("Force sleep (even when not in standby)"), config.plugins.elektro.force,
347                                 _("Forces deep standby, even when not in standby mode. Scheduled recordings remain unaffected.")),
348                         getConfigListEntry(_("Avoid deep standby when HDD is active, e.g. for FTP"), config.plugins.elektro.hddsleep,
349                                 _("Wait for the HDD to enter sleep mode. Depending on the configuration this can prevent the box entirely from entering deep standby mode.")),
350                         getConfigListEntry(_("Check IPs (press OK to edit)"), config.plugins.elektro.IPenable,
351                                 _("This list of IP addresses is checked. Elektro waits until addresses no longer responds to ping.")),
352                         getConfigListEntry(_("Don't wake up"), config.plugins.elektro.dontwakeup,
353                                 _("Do not wake up at the end of next deep standby interval.")),
354                         getConfigListEntry(_("Holiday mode (experimental)"), config.plugins.elektro.holiday,
355                                 _("The box always enters deep standby mode, except for recording.")),
356                         getConfigListEntry(_("Show in"), config.plugins.elektro.menu,
357                                 _("Specify whether plugin shall show up in plugin menu or extensions menu (needs GUI restart)")),
358                         getConfigListEntry(_("Name"), config.plugins.elektro.name,
359                                 _("Specify plugin name to be used in menu (needs GUI restart).")),
360                         getConfigListEntry(_("Description"), config.plugins.elektro.description,
361                                 _("Specify plugin description to be used in menu (needs GUI restart).")),               
362                         ]               
363                                 
364                 ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changed)
365                 
366                 def selectionChanged():
367                         if self["config"].current:
368                                 self["config"].current[1].onDeselect(self.session)
369                         self["config"].current = self["config"].getCurrent()
370                         if self["config"].current:
371                                 self["config"].current[1].onSelect(self.session)
372                         for x in self["config"].onSelectionChanged:
373                                 x()
374                                 
375                 self["config"].selectionChanged = selectionChanged
376                 self["config"].onSelectionChanged.append(self.configHelp)
377                 
378                 self["key_red"] = Button(_("Cancel"))
379                 self["key_green"] = Button(_("Ok"))
380                 self["key_yellow"] = Button(_("Help"))
381                 self["key_blue"] = Button(_("Times"))
382                 self["help"] = StaticText()
383                 
384                 self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
385                 {
386                         "red": self.keyCancel,
387                         "green": self.keySave,
388                         "yellow": self.help,
389                         "blue": self.profile,
390                         "save": self.keySave,
391                         "cancel": self.keyCancel,
392                         "ok": self.keyOK,
393                 }, -2)
394                 
395                 # Trigger change
396                 self.changed()
397
398                 self.onLayoutFinish.append(self.setCustomTitle)
399
400         def setCustomTitle(self):
401                 self.setTitle(config.plugins.elektro.name.value + " "  + _("Ver.") + " " + elektro_pluginversion)
402
403         def configHelp(self):
404                 cur = self["config"].getCurrent()
405                 self["help"].text = cur[2]
406
407         def keyOK(self):
408                 ConfigListScreen.keyOK(self)
409                 sel = self["config"].getCurrent()[1]
410                 if sel == config.plugins.elektro.IPenable:
411                         self.session.open(ElektroIP)
412
413         def changed(self):
414                 for x in self.onChangedEntry:
415                         try:
416                                 x()
417                         except Exception:
418                                 pass    
419                         
420         def getCurrentEntry(self):
421                 return self["config"].getCurrent()[0]
422
423         def getCurrentValue(self):
424                 return str(self["config"].getCurrent()[1].getText())
425                 
426         def help(self):
427                 if language.getLanguage()[:2] == "de":
428                         self.session.open(Console,_("Showing Elektro readme.txt"),["cat %s" % elektro_readme_de])
429                 else:
430                         self.session.open(Console,_("Showing Elektro readme.txt"),["cat %s" % elektro_readme])
431
432         def profile(self):
433                 self.session.open(ElektroProfile)
434
435 class DoElektro(Screen):
436         skin = """ <screen position="center,center" size="300,300" title="Elektro Plugin Menu" > </screen>"""
437         
438         def __init__(self,session):
439                 Screen.__init__(self,session)
440                 
441                 print pluginPrintname, "Starting up Version", elektro_pluginversion
442                 
443                 self.session = session
444                 
445                 # Make sure wakeup time is set.
446                 self.setNextWakeuptime()
447                 
448                 # If we didn't wake up by a timer we don't want to go to sleep any more.
449                 # Unforturnately it is not possible to use getFPWasTimerWakeup()
450                 # Therfore we're checking wheter there is a recording starting within
451                 # the next five min             
452                 self.dontsleep = False
453                 
454                 #Let's assume we got woken up manually
455                 timerWakeup = False
456                 
457                 #Is a recording already runniong ->woken up by a timer
458                 if self.session.nav.RecordTimer.isRecording():
459                         timerWakeup = True
460                 # Is the next timer within 5 min -> woken up by a timer 
461                 if abs(self.session.nav.RecordTimer.getNextRecordingTime() - time()) <= 360:
462                         timerWakeup = True
463                         
464                 # Did we wake up by Elektro?
465                 # Let's hope this get's run early enaugh, and this get's run
466                 # before the requested wakeup-time (should be the case)
467                 #
468                 if abs(ElektroWakeUpTime - time()) <= 360:
469                         timerWakeup = True      
470                         
471                 # If the was a manual wakeup: Don't go to sleep 
472                 if timerWakeup == False:
473                         self.dontsleep = True
474                 
475                 
476                 #Check whether we should try to sleep:
477                 trysleep = config.plugins.elektro.standbyOnBoot.value
478                 
479                 #Don't go to sleep when this was a manual wakeup and the box shouldn't go to standby
480                 if timerWakeup == False and     config.plugins.elektro.standbyOnManualBoot.value == False:
481                         trysleep = False
482                         
483         
484                 #if waken up by timer and configured ask whether to go to sleep.
485                 if trysleep:
486                         self.TimerStandby = eTimer()
487                         self.TimerStandby.callback.append(self.CheckStandby)
488                         self.TimerStandby.startLongTimer(elektrosleeptime)
489                         print pluginPrintname, "Set up standby timer"
490
491                 self.TimerSleep = eTimer()
492                 self.TimerSleep.callback.append(self.CheckElektro)
493                 self.TimerSleep.startLongTimer(elektrostarttime)
494                 print pluginPrintname, "Set up sleep timer"             
495                 if debug:
496                         print pluginPrintname, "Translation test:", _("Standby on boot")
497                 
498         def clkToTime(self, clock):
499                 return ( (clock.value[0]) * 60 + (int)(clock.value[1]) )  * 60
500                 
501         def getTime(self):
502                 ltime = localtime();
503                 return ( (int)(ltime.tm_hour) * 60 + (int)(ltime.tm_min) ) * 60
504         
505         def getPrintTime(self, secs):
506                 return strftime("%H:%M:%S", gmtime(secs))
507
508         
509         # This function converts the time into the relative Timezone where the day starts at "nextday"
510         # This is done by substracting nextday from the current time. Negative times are corrected using the mod-operator
511         def getReltime(self, time):
512                 if config.plugins.elektro.profile.value == "1":
513                         nextday = self.clkToTime(config.plugins.elektro.nextday)
514                 else:
515                         nextday = self.clkToTime(config.plugins.elektro.nextday2)
516                 return (time - nextday) %  (24 * 60 * 60)
517                 
518         
519         def CheckStandby(self):
520                 print pluginPrintname, "Showing Standby Sceen"
521                 try:
522                         self.session.openWithCallback(self.DoElektroStandby,MessageBox,_("Go to Standby now?"),type = MessageBox.TYPE_YESNO,
523                                         timeout = config.plugins.elektro.standbyOnBootTimeout.value)            
524                 except:
525                         # Couldn't be shown. Restart timer.
526                         print pluginPrintname, "Failed Showing Standby Sceen "
527                         self.TimerStandby.startLongTimer(elektrostarttime)
528
529
530         def DoElektroStandby(self,retval):
531                 if (retval):
532                         #Yes, go to sleep
533                         Notifications.AddNotification(Standby.Standby)
534                 
535
536                         
537         def setNextWakeuptime(self):
538                 # Do not set a wakeup time if
539                 #  - Elektro isn't enabled
540                 #  - Elektro shouldn't wake up
541                 #  - Holiday mode is turned on
542                 if ((config.plugins.elektro.enable.value == False) 
543                       or (config.plugins.elektro.dontwakeup.value == True)
544                       or config.plugins.elektro.holiday.value == True): 
545                         global ElektroWakeUpTime
546                         ElektroWakeUpTime = -1
547                         return
548                         
549                 time_s = self.getTime()
550                 ltime = localtime()
551                 
552                 #print pluginPrintname, "Nextday:", time.ctime(self.clkToTime(config.plugins.elektro.nextday))
553                 # If it isn't past next-day time we need yesterdays settings
554                 #
555                 # Check whether we wake up today or tomorrow
556                 # Relative Time is needed for this
557                 if config.plugins.elektro.profile.value == "1":
558                         if time_s < self.clkToTime(config.plugins.elektro.nextday):
559                                 day = (ltime.tm_wday - 1) % 7
560                         else:
561                                 day = ltime.tm_wday
562                         time_s = self.getReltime(time_s)
563                         wakeuptime = self.getReltime(self.clkToTime(config.plugins.elektro.wakeup[day]))
564                 else:
565                         if time_s < self.clkToTime(config.plugins.elektro.nextday2):
566                                 day = (ltime.tm_wday - 1) % 7
567                         else:
568                                 day = ltime.tm_wday
569                         time_s = self.getReltime(time_s)
570                         wakeuptime = self.getReltime(self.clkToTime(config.plugins.elektro.wakeup2[day]))
571                 
572                 # Lets see if we already woke up today
573                 if wakeuptime < time_s:
574                         #yes we did -> Next wakeup is tomorrow
575                         if debug:                       
576                                 print pluginPrintname, "Wakeup tomorrow"
577                         day = (day + 1) % 7
578                         if config.plugins.elektro.profile.value == "1":
579                                 wakeuptime = self.getReltime(self.clkToTime(config.plugins.elektro.wakeup[day]))
580                         else:
581                                 wakeuptime = self.getReltime(self.clkToTime(config.plugins.elektro.wakeup2[day]))
582                 
583                 # Tomorrow we'll wake up erly-> Add a full day.
584                 if wakeuptime < time_s:
585                         wakeuptime = wakeuptime + 24 * 60 * 60
586                 
587                 # The next wakeup will be in wakupin seconds
588                 wakeupin = wakeuptime - time_s
589                 
590                 # Now add this to the current time to get the wakeuptime
591                 wakeuptime = (int)(time()) + wakeupin
592                 
593                 #Write everything to the global variable
594                 ElektroWakeUpTime = wakeuptime
595                         
596                         
597         def CheckElektro(self):
598                 # first set the next wakeuptime - it would be much better to call that function on sleep. This will be a todo!
599                 self.setNextWakeuptime()
600         
601                 #convert to seconds
602                 time_s = self.getTime()
603                 ltime = localtime()
604                 
605                 print pluginPrintname, "Testtime;", self.getPrintTime(2 * 60 * 60)
606                 
607                 #Which day is it? The next day starts at nextday
608                 if debug:
609                         print pluginPrintname, "wday 1:", str(ltime.tm_wday)
610                 if config.plugins.elektro.profile.value == "1":
611                         if time_s < self.clkToTime(config.plugins.elektro.nextday):
612                                 day = (ltime.tm_wday - 1) % 7
613                         else:
614                                 day = ltime.tm_wday
615                 else:
616                         if time_s < self.clkToTime(config.plugins.elektro.nextday2):
617                                 day = (ltime.tm_wday - 1) % 7
618                         else:
619                                 day = ltime.tm_wday
620                 if debug:       
621                         print pluginPrintname, "wday 2:", str(day)
622                 
623                 #Let's get the day
624                 if config.plugins.elektro.profile.value == "1":
625                         wakeuptime = self.clkToTime(config.plugins.elektro.wakeup[day])
626                         sleeptime = self.clkToTime(config.plugins.elektro.sleep[day])
627                 else:
628                         wakeuptime = self.clkToTime(config.plugins.elektro.wakeup2[day])
629                         sleeptime = self.clkToTime(config.plugins.elektro.sleep2[day])
630
631                 print pluginPrintname, "Current time:", self.getPrintTime(time_s)
632                 print pluginPrintname, "Wakeup time:", self.getPrintTime(wakeuptime)
633                 print pluginPrintname, "Sleep time:", self.getPrintTime(sleeptime)
634                 
635                 #convert into relative Times
636                 time_s = self.getReltime(time_s)
637                 wakeuptime  = self.getReltime(wakeuptime)
638                 sleeptime = self.getReltime(sleeptime)
639                 
640                 if debug:
641                         print pluginPrintname, "Current Rel-time:", self.getPrintTime(time_s)
642                         print pluginPrintname, "Wakeup Rel-time:", self.getPrintTime(wakeuptime)
643                         print pluginPrintname, "Sleep Rel-time:", self.getPrintTime(sleeptime)
644                 
645                 
646                 #let's see if we should be sleeping
647                 trysleep = False
648                 if time_s < (wakeuptime - elektroShutdownThreshold): # Wakeup is in the future -> sleep!
649                         trysleep = True
650                         print pluginPrintname, "Wakeup!", str(time_s), " <", str(wakeuptime)
651                 if sleeptime < time_s : #Sleep is in the past -> sleep!
652                         trysleep = True
653                         print pluginPrintname, "Sleep:", str(sleeptime), " <", str(time_s)
654                 
655                 #We are not tying to go to sleep anymore -> maybe go to sleep again the next time
656                 if trysleep == False:
657                         self.dontsleep = False
658                 
659                 #The User aborted to got to sleep -> Don't go to sleep.
660                 if self.dontsleep:
661                         trysleep = False
662                         
663                 # If we are in holydaymode we should try to got to sleep anyway
664                 # This should be set after self.dontsleep has been handled
665                 if config.plugins.elektro.holiday.value:
666                         trysleep = True
667                 
668                 # We are not enabled -> Dont go to sleep (This could have been catched earlier!)
669                 if config.plugins.elektro.enable.value == False:
670                         trysleep = False
671                 
672                 # Only go to sleep if we are in standby or sleep is forced by settings
673                 if  not ((Standby.inStandby) or (config.plugins.elektro.force.value == True) ):
674                         trysleep = False
675                 
676                 # No Sleep while recording
677                 if self.session.nav.RecordTimer.isRecording():
678                         trysleep = False
679                 
680                 # No Sleep on Online IPs - joergm6
681                 if trysleep == True and config.plugins.elektro.IPenable.value == True:
682                         for i in range(10):
683                                 ip = "%d.%d.%d.%d" % tuple(config.plugins.elektro.ip[i].value)
684                                 if ip != "0.0.0.0":
685                                         if ping.doOne(ip,0.1) != None:
686                                                 print pluginPrintname, ip, "online"
687                                                 trysleep = False
688                                                 break
689
690                 # No Sleep on HDD running - joergm6
691                 if (config.plugins.elektro.hddsleep.value == True) and (harddiskmanager.HDDCount() > 0):
692                         hddlist = harddiskmanager.HDDList()
693                         if not hddlist[0][1].isSleeping():
694                                 trysleep = False
695                 
696                 # Will there be a recording in a short while?
697                 nextRecTime = self.session.nav.RecordTimer.getNextRecordingTime()
698                 if  (nextRecTime > 0) and (nextRecTime - (int)(time()) <  elektroShutdownThreshold):
699                         trysleep = False
700                         
701                 # Looks like there really is a reason to go to sleep -> Lets try it!
702                 if trysleep:
703                         #self.();
704                         try:
705                                 self.session.openWithCallback(self.DoElektroSleep, MessageBox, _("Go to sleep now?"),type = MessageBox.TYPE_YESNO,timeout = 60) 
706                                 if config.plugins.elektro.profileShift.value == True:
707                                         config.plugins.elektro.profile.value = "1" if config.plugins.elektro.profile.value == "2" else "2"
708                                         config.plugins.elektro.profile.save()
709                                         self.setNextWakeuptime()
710                         except:
711                                 #reset the timer and try again
712                                 self.TimerSleep.startLongTimer(elektrostarttime) 
713                                 
714                 #set Timer, which calls this function again.
715                 self.TimerSleep.startLongTimer(elektrostarttime) 
716                 
717                 
718
719
720         def DoElektroSleep(self,retval):
721                 if (retval):
722                         # os.system("wall 'Powermanagent does Deepsleep now'")
723                         #  Notifications.AddNotification(TryQuitMainloop,1)
724                         # 1 = Deep Standby -> enigma2:/doc/RETURNCODES
725                         
726                         global inTryQuitMainloop
727                         if Standby.inTryQuitMainloop == False:
728                                 self.session.open(Standby.TryQuitMainloop, 1) # <- This might not work reliably
729                                 #quitMainloop(1)
730                 else:
731                         # Dont try to sleep until next wakeup
732                         self.dontsleep = True
733                         #Start the timer again
734                         self.TimerSleep.startLongTimer(elektrostarttime) 
735