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