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