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