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