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