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