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