fix versioned depends lines
[enigma2-plugins.git] / fancontrol2 / src / plugin.py
1 # FanControl2
2 # joergm6 IHAD
3 import time
4 import os
5 from __init__ import _
6
7 from globals import *
8
9 from enigma import eTimer, eSize
10
11 # Config
12 from Components.config import configfile, config, ConfigSubsection, ConfigNumber, ConfigInteger, ConfigSlider, ConfigSelection, ConfigYesNo, ConfigText
13 from Components.config import getConfigListEntry
14 from Components.Label import Label
15 from Components.Sources.StaticText import StaticText
16 from Components.Sources.Progress import Progress
17
18 # Startup/shutdown notification
19 from Tools import Notifications
20 from Sensors import sensors
21 from time import gmtime, strftime
22 import datetime
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 from Screens.MessageBox import MessageBox
34 from Screens.Standby import TryQuitMainloop
35
36 # GUI (Components)
37 from Components.ActionMap import ActionMap
38 from Components.ActionMap import NumberActionMap
39 from Components.Harddisk import harddiskmanager
40
41 def main(session,**kwargs):
42         try:
43                 session.open(FanControl2Plugin)
44         except:
45                 FClog("Pluginexecution failed")
46
47 def mainMonitor(session,**kwargs):
48         try:
49                 session.open(FanControl2Monitor)
50         except:
51                 FClog("Pluginexecution failed")
52
53 def Test0(wert):
54         return (1 if wert<=0 else wert)
55
56 def skal(x, x1, x2, y1, y2):
57         if x > x2: return y2
58         if x < x1: return y1
59         m = (y2 - y1) / Test0(x2 - x1)
60         y = m * x + y1
61         return y
62
63 def FClog(wert):
64         print "[FanControl2]",wert
65         while len(FC2Log) > config.plugins.FanControl.LogCount.value:
66                 del FC2Log[5]
67         FC2Log.append(strftime("%H:%M:%S ") + wert)
68         if config.plugins.FanControl.EnableEventLog.value:
69                 if Free(config.plugins.FanControl.LogPath.value):
70                         try:
71                                 f = open(config.plugins.FanControl.LogPath.value + "FC2events.txt","a")
72                                 try:
73                                         f.write(strftime("%H:%M:%S ") + wert + "\r\n")
74                                 finally:
75                                         f.close()
76                         except IOError:
77                                 FC2Log.append(strftime("%H:%M:%S ") + "Event-Log-Error")
78
79 def FCdata():
80         global DataMinute
81         if strftime("%M")!=DataMinute and config.plugins.FanControl.EnableDataLog.value:
82                 DataMinute = strftime("%M")
83                 if Free(config.plugins.FanControl.LogPath.value):
84                         try:
85                                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","a")
86                                 try:
87                                         f.write(strftime("%Y.%m.%d %H:%M"))
88                                         for count in range(6):
89                                                 f.write(";" + str(FC2werte[count]).replace(".",_(".")))
90                                         templist = sensors.getSensorsList(sensors.TYPE_TEMPERATURE)
91                                         tempcount = len(templist)
92                                         for count in range(tempcount):
93                                                 f.write(";" + str(sensors.getSensorValue(count)))
94                                         f.write("\r\n")
95                                 finally:
96                                         f.close()
97                         except IOError:
98                                 FC2Log.append(strftime("%H:%M:%S ") + "Event-Log-Error")
99
100 def Free(dir):
101         if not os.path.exists(dir):
102                 return False
103         s = os.statvfs(dir)
104         return (s.f_bsize * s.f_bavail / 1024 / 1024) > 10
105
106 def getVoltage(fanid):
107         f = open("/proc/stb/fp/fan_vlt", "r")
108         value = int(f.readline().strip(), 16)
109         f.close()
110         return value
111
112 def setVoltage(fanid, value):
113         if value > 255:
114                 return
115         f = open("/proc/stb/fp/fan_vlt", "w")
116         f.write("%x" % value)
117         f.close()
118
119 def getPWM(fanid):
120         f = open("/proc/stb/fp/fan_pwm", "r")
121         value = int(f.readline().strip(), 16)
122         f.close()
123         return value
124
125 def setPWM(fanid, value):
126         if value > 255:
127                 return
128         f = open("/proc/stb/fp/fan_pwm", "w")
129         f.write("%x" % value)
130         f.close()
131
132 #Configuration
133 config.plugins.FanControl = ConfigSubsection()
134 config.plugins.FanControl.Fan = ConfigSelection(choices = [("disabled", _("disabled")), ("aus", _("Control disabled")), ("3pin", _("3Pin")), ("4pin", _("4Pin"))], default = "disabled")
135 config.plugins.FanControl.StandbyOff = ConfigSelection(choices = [("false", _("no")), ("true", _("yes")), ("trueRec", _("yes, Except for Recording or HDD"))], default="false")
136 config.plugins.FanControl.minRPM = ConfigSlider(default = 500, increment = 50, limits = (0, 1000))
137 config.plugins.FanControl.maxRPM = ConfigSlider(default = 3000, increment = 50, limits = (500, 6000))
138 config.plugins.FanControl.temp = ConfigSlider(default = 40, increment = 1, limits = (30, 50))
139 config.plugins.FanControl.tempmax = ConfigSlider(default = 50, increment = 1, limits = (35, 55))
140 config.plugins.FanControl.pwm = ConfigSlider(default = 130, increment = 5, limits = (0, 255))
141 config.plugins.FanControl.vlt = ConfigSlider(default = 255, increment = 5, limits = (0, 255))
142 config.plugins.FanControl.ShowError = ConfigSelection(choices = [("false", _("do nothing")), ("true", _("display Info")), ("shutdown", _("Box Shutdown"))], default="true")
143 config.plugins.FanControl.ShutdownTemp = ConfigInteger(default = 65,limits = (50, 80))
144 config.plugins.FanControl.AddOverheat = ConfigInteger(default = 0,limits = (0, 9))
145 config.plugins.FanControl.DisableDMM = ConfigYesNo(default = False)
146 config.plugins.FanControl.LogCount = ConfigInteger(default = 40,limits = (40, 999))
147 config.plugins.FanControl.LogPath = ConfigText(default="/tmp/", fixed_size=False)
148 config.plugins.FanControl.DeleteData = ConfigSelection(choices = [("0", _("no")), ("2", "2"), ("3", "3"), ("7", "7"), ("14", "14"), ("30", "30")], default="0")
149 config.plugins.FanControl.EnableDataLog = ConfigYesNo(default = False)
150 config.plugins.FanControl.EnableEventLog = ConfigYesNo(default = False)
151 config.plugins.FanControl.CheckHDDTemp = ConfigSelection(choices = [("false", _("no")), ("true", _("yes")), ("auto", _("auto")), ("never", _("never"))], default="auto")
152 config.plugins.FanControl.MonitorInExtension = ConfigYesNo(default = True)
153 config.plugins.FanControl.Multi = ConfigSelection(choices = [(1, "RPM"), (2, "RPM/2")], default = 2)
154
155 def GetFanRPM():
156         global RPMread
157         f = open("/proc/stb/fp/fan_speed", "r")
158         value = int(f.readline().strip()[:-4])
159         f.close()
160         if value > 0:
161                 RPMread = 0
162         else:
163                 RPMread += 1
164         value = int(value / config.plugins.FanControl.Multi.value)
165         return value
166
167 def GetBox():
168         B = Box
169         if os.path.exists("/proc/stb/info/model"):
170                 f = open("/proc/stb/info/model")
171                 B = f.readline()
172                 f.close()
173         return B
174
175 def isDMMdisabled():
176         value = False
177         if os.path.exists("/usr/lib/enigma2/python/Components/FanControl.py"):
178                 FCfile = open("/usr/lib/enigma2/python/Components/FanControl.py", "r")
179                 text=FCfile.read()
180                 FCfile.close()
181                 if text.find("#Disabled by FC2 config.misc.standbyCounter.addNotifier") is not -1:
182                         value = True
183         return value
184
185 def disableDMM():
186         if os.path.exists("/usr/lib/enigma2/python/Components/FanControl.py"):
187                 FCfile = open("/usr/lib/enigma2/python/Components/FanControl.py", "r")
188                 text=FCfile.read()
189                 FCfile.close()
190                 FCfile = open("/usr/lib/enigma2/python/Components/FanControl.py", "w")
191                 text=text.replace("config.misc.standbyCounter.addNotifier","#Disabled by FC2 config.misc.standbyCounter.addNotifier")
192                 text=FCfile.write(text)
193                 FCfile.close()
194                 FClog("DMM-fancontrol disabled - please restart E2")
195
196 def enableDMM():
197         if os.path.exists("/usr/lib/enigma2/python/Components/FanControl.py"):
198                 FCfile = open("/usr/lib/enigma2/python/Components/FanControl.py", "r")
199                 text=FCfile.read()
200                 FCfile.close()
201                 FCfile = open("/usr/lib/enigma2/python/Components/FanControl.py", "w")
202                 text=text.replace("#Disabled by FC2 config.misc.standbyCounter.addNotifier","config.misc.standbyCounter.addNotifier")
203                 text=FCfile.write(text)
204                 FCfile.close()
205
206 class FanControl2Test(ConfigListScreen,Screen):
207         skin = """
208                 <screen position="center,center" size="630,300" title="Fan Control 2 - Test" >
209                         <widget source="TextTest1" render="Label" position="5,20" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
210                         <widget source="TextTest2" render="Label" position="5,50" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
211                         <widget source="TextTest3" render="Label" position="5,80" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
212                         <widget source="TextTest4" render="Label" position="5,130" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
213                         <widget source="TextTest5" render="Label" position="5,160" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
214                         <widget source="TextTest6" render="Label" position="5,190" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
215                         <widget source="TextTest7" render="Label" position="5,220" size="620,30" zPosition="10" font="Regular;20" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
216                 </screen>"""
217
218
219         def __init__(self, session, args = 0):
220                 self.session = session
221                 Screen.__init__(self, session)
222
223                 self.timer = eTimer()
224                 self.timer.callback.append(self.DoTest)
225                 self.timer.start(1000, True)
226
227                 self["TextTest1"] = StaticText()
228                 self["TextTest2"] = StaticText()
229                 self["TextTest3"] = StaticText()
230                 self["TextTest4"] = StaticText()
231                 self["TextTest5"] = StaticText()
232                 self["TextTest6"] = StaticText()
233                 self["TextTest7"] = StaticText()
234
235                 self["TextTest1"].setText(_("please wait (until 3min)..."))
236
237                 self["actions"] = ActionMap(["OkCancelActions"], 
238                 {
239                         "ok": self.cancel,
240                         "cancel": self.cancel
241                 }, -1)
242
243         def VoltUp(self):
244                 while GetFanRPM() < 100 and self.i < 255:
245                         setVoltage(self.id,self.i)
246                         time.sleep(0.3)
247                         self.i += 1
248
249         def VoltDown(self):
250                 while GetFanRPM() > 100 and self.i > 0:
251                         setVoltage(self.id,self.i)
252                         time.sleep(1)
253                         self.i -= 1
254
255         def DoTest(self):
256                 self.id = 0
257                 self.i = 0
258                 self.last = 0
259                 self.rpm = 0
260                 SaveAktVLT = AktVLT
261                 SaveAktPWM = AktPWM
262                 SaveFan = config.plugins.FanControl.Fan.value
263                 config.plugins.FanControl.Fan.value = "aus"
264                 if SaveFan == "4pin":
265                         setPWM(self.id,0)
266                         time.sleep(10)
267                         while GetFanRPM() < 100 and self.i < 255:
268                                 setPWM(self.id,self.i)
269                                 time.sleep(0.3)
270                                 self.i += 1
271                         time.sleep(2)
272                         self.last=GetFanRPM()
273                         self["TextTest1"].setText(_("Min Fan Start %d rpm at PWM=%d") % (self.last, self.i))
274                         while GetFanRPM() > 100 and self.i > 1:
275                                 setPWM(self.id,self.i)
276                                 time.sleep(1)
277                                 self.i -= 1
278                         ok = ("OK" if config.plugins.FanControl.minRPM.value >= self.last else (("!!>%d" % config.plugins.FanControl.minRPM.value)))
279                         self["TextTest2"].setText(_("Min Fan Stop %d rpm at PWM=%d (%s)") % (self.last, self.i, ok))
280
281                         setPWM(self.id,255)
282                         time.sleep(6)
283                         self.rpm = GetFanRPM()
284                         ok = ("OK" if config.plugins.FanControl.maxRPM.value <= self.rpm else ("!!<%d" % (config.plugins.FanControl.maxRPM.value)))
285                         self["TextTest3"].setText(_("Max Fan %d rpm at PWM=255 (%s)") % (self.rpm, ok))
286 # extended
287                         self["TextTest4"].setText(_("Extended Control Range"))
288                         setPWM(self.id,0)
289                         time.sleep(10)
290                         self.rpm = GetFanRPM()
291                         if self.rpm > 0:
292                                 setVoltage(self.id,0)
293                                 time.sleep(10)
294                                 self.VoltUp()
295                                 time.sleep(3)
296                                 self.last=GetFanRPM()
297                                 self["TextTest5"].setText(_("Min Fan Start %d rpm at VLT=%d and PWM=0") % (self.last, self.i))
298                                 self.VoltDown()
299                                 ok = ("OK" if config.plugins.FanControl.minRPM.value >= self.last else (("!!>%d" % config.plugins.FanControl.minRPM.value)))
300                                 self["TextTest6"].setText(_("Min Fan Stop %d rpm at VLT=%d and PWM=0 (%s)") % (self.last, self.i, ok))
301
302                         setPWM(self.id,255)
303                         setVoltage(self.id,255)
304                         time.sleep(6)
305                         self.rpm = GetFanRPM()
306                         ok = ("OK" if config.plugins.FanControl.maxRPM.value <= self.rpm else ("!!<%d" % (config.plugins.FanControl.maxRPM.value)))
307                         self["TextTest7"].setText(_("Max Fan %d rpm at PWM=255 and VLT=255 (%s)") % (self.rpm, ok))
308
309                 if SaveFan == "3pin":
310                         setVoltage(self.id,0)
311                         time.sleep(10)
312                         self.VoltUp()
313                         time.sleep(3)
314                         self.last=GetFanRPM()
315                         self["TextTest1"].setText(_("Min Fan Start %d rpm at VLT=%d") % (self.last, self.i))
316                         self.VoltDown()
317                         ok = ("OK" if config.plugins.FanControl.minRPM.value >= self.last else ("!!>%d" % (config.plugins.FanControl.minRPM.value)))
318                         self["TextTest2"].setText(_("Min Fan Stop %d rpm at VLT=%d (%s)") % (self.last, self.i, ok))
319
320                         setVoltage(self.id,255)
321                         time.sleep(6)
322                         ok = ("OK" if config.plugins.FanControl.maxRPM.value <= GetFanRPM() else ("!!<%d" % (config.plugins.FanControl.maxRPM.value)))
323                         self["TextTest3"].setText(_("Max Fan %d rpm at VLT=255 (%s)") % (GetFanRPM(), ok))
324
325                 setVoltage(self.id,SaveAktVLT)
326                 setPWM(self.id,SaveAktPWM)
327                 config.plugins.FanControl.Fan.value = SaveFan
328
329         def cancel(self):
330                 self.close(False,self.session)
331
332 class FanControl2Monitor(Screen, ConfigListScreen):
333         skin = """
334                 <screen position="center,center" size="600,260" title="Fan Control 2 - Monitor">
335
336                         <widget source="TxtTemp0" render="Label" position="5,30" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
337                         <widget source="TxtTemp1" render="Label" position="5,50" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
338                         <widget source="TxtTemp2" render="Label" position="5,70" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
339                         <widget source="TxtTemp3" render="Label" position="5,90" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
340                         <widget source="TxtTemp4" render="Label" position="5,110" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
341                         <widget source="TxtTemp5" render="Label" position="5,130" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
342                         <widget source="TxtTemp6" render="Label" position="5,150" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
343                         <widget source="TxtTemp7" render="Label" position="5,170" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
344                         <widget source="TxtHDD" render="Label" position="5,190" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
345                         <widget source="TxtFan" render="Label" position="5,210" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
346                         <widget name="TxtMinTemp" position="260,20" size="50,12" zPosition="1" font="Regular;12" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
347                         <widget source="TxtFC2Temp" render="Label" position="398,20" size="50,12" zPosition="1" font="Regular;17" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
348                         <widget name="TxtMaxTemp" position="535,20" size="50,12" zPosition="1" font="Regular;12" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
349                         <widget source="ProTemp0" render="Progress" position="260,40" size="325,5" borderWidth="1" />
350                         <widget source="ProTemp1" render="Progress" position="260,60" size="325,5" borderWidth="1" />
351                         <widget source="ProTemp2" render="Progress" position="260,80" size="325,5" borderWidth="1" />
352                         <widget source="ProTemp3" render="Progress" position="260,100" size="325,5" borderWidth="1" />
353                         <widget source="ProTemp4" render="Progress" position="260,120" size="325,5" borderWidth="1" />
354                         <widget source="ProTemp5" render="Progress" position="260,140" size="325,5" borderWidth="1" />
355                         <widget source="ProTemp6" render="Progress" position="260,160" size="325,5" borderWidth="1" />
356                         <widget source="ProTemp7" render="Progress" position="260,180" size="325,5" borderWidth="1" />
357                         <widget source="ProHDD" render="Progress" position="260,200" size="325,5" borderWidth="1" />
358                         <widget source="ProFan" render="Progress" position="260,220" size="325,5" borderWidth="1" />
359
360                 </screen>"""
361         
362         def __init__(self, session, args = None):
363                 Screen.__init__(self, session)
364
365                 self.temp_timer = eTimer()
366                 self.temp_timer.callback.append(self.updateTemp)
367
368                 for count in range(8):
369                         self["ProTemp%d" % count] = Progress()
370                         self["TxtTemp%d" % count] = StaticText("")
371                 self["ProHDD"] = Progress()
372                 self["TxtHDD"] = StaticText("")
373                 self["ProFan"] = Progress()
374                 self["TxtFan"] = StaticText("")
375                 self["TxtFC2Temp"] = StaticText("")
376                 self["TxtMinTemp"] = Label("30")
377                 self["TxtMaxTemp"] = Label("55")
378
379                 self["actions"] = ActionMap(["OkCancelActions", "EPGSelectActions"], 
380                 {
381                         "ok": self.cancel,
382                         "cancel": self.cancel,
383                         "info": self.getHDD
384                 }, -1)
385
386                 self.onLayoutFinish.append(self.updateTemp)
387
388         def updateTemp(self):
389                 templist = sensors.getSensorsList(sensors.TYPE_TEMPERATURE)
390                 tempcount = len(templist)
391                 for count in range(tempcount):
392                         tt = sensors.getSensorValue(count)
393                         self["ProTemp%d" % count].value = int((tt-30)*100/(55-30)) 
394                         if sensors.getSensorName(count) == "undefined":
395                                 self["TxtTemp%d" % count].setText(_("%s   %02d C") % (TempName[count], tt))
396                         else:
397                                 self["TxtTemp%d" % count].setText(_("%s   %02d C") % (sensors.getSensorName(count), tt))
398                 if harddiskmanager.HDDCount() > 0:
399                         if max(AktHDD) > 0:
400                                 self["ProHDD"].value = int((max(AktHDD)-30)*100/(55-30)) 
401                                 self["TxtHDD"].setText(_("%s   %02d C") % ("HDD", max(AktHDD)))
402                         elif config.plugins.FanControl.CheckHDDTemp.value !="never":
403                                 self["TxtHDD"].setText(_("press Info for HDD-Temp"))
404                 self["TxtFan"].setText(_("Current rpm  %4d") % (AktRPM))
405                 self["ProFan"].value = int((AktRPM-config.plugins.FanControl.minRPM.value)*100/Test0(config.plugins.FanControl.maxRPM.value-config.plugins.FanControl.minRPM.value))
406                 if tempcount>1:
407                         self["TxtFC2Temp"].setText("%4.1f" % AktTemp)
408                 self.temp_timer.start(2000, True)
409         
410         def cancel(self):
411                 self.close(False,self.session)
412
413         def getHDD(self):
414                 if harddiskmanager.HDDCount() > 0 and config.plugins.FanControl.CheckHDDTemp.value !="never":
415                         GetHDDtemp(True)
416                         for hdd in harddiskmanager.HDDList():
417                                 if hdd[1].isSleeping():
418                                         (stat,wert)=getstatusoutput("hdparm -y %s" % hdd[1].getDeviceName())
419
420 class FanControl2SpezialSetup(Screen, ConfigListScreen):
421         skin = """
422                 <screen position="center,center" size="600,320" title="Fan Control 2 - Setup" >
423                         <widget name="config" position="10,20" size="580,290" scrollbarMode="showOnDemand" />
424                 </screen>"""
425
426         def __init__(self, session, args = None):
427                 Screen.__init__(self, session)
428
429                 config.plugins.FanControl.DisableDMM.value = isDMMdisabled()
430                 self.HDDmode = config.plugins.FanControl.CheckHDDTemp.value
431                 self.MonitorMode = config.plugins.FanControl.MonitorInExtension.value
432
433                 self.list = []
434                 self.list.append(getConfigListEntry(_("Action in case of Fan failure"), config.plugins.FanControl.ShowError))
435                 self.list.append(getConfigListEntry(_("Box shutdown at Temperature (C)"), config.plugins.FanControl.ShutdownTemp))
436                 self.list.append(getConfigListEntry(_("increases overheating protection to (C)"), config.plugins.FanControl.AddOverheat))
437                 self.list.append(getConfigListEntry(_("read HDD-Temperature in HDD-Standby-Mode"), config.plugins.FanControl.CheckHDDTemp))
438                 self.list.append(getConfigListEntry(_("disable DMM-FanControl"), config.plugins.FanControl.DisableDMM))
439                 self.list.append(getConfigListEntry(_("Show Monitor in Extension-Menu"), config.plugins.FanControl.MonitorInExtension))
440                 self.list.append(getConfigListEntry(_("Number of WebIF-Log-Entries"), config.plugins.FanControl.LogCount))
441                 self.list.append(getConfigListEntry(_("Logging path"), config.plugins.FanControl.LogPath))
442                 self.list.append(getConfigListEntry(_("Enable Data Logging"), config.plugins.FanControl.EnableDataLog))
443                 self.list.append(getConfigListEntry(_("Auto-Delete Data older than (Days)"), config.plugins.FanControl.DeleteData))
444                 self.list.append(getConfigListEntry(_("Enable Event Logging"), config.plugins.FanControl.EnableEventLog))
445                 ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
446
447                 self["actions"] = ActionMap(["OkCancelActions"], 
448                 {
449                         "ok": self.keyOK,
450                         "cancel": self.cancel
451                 }, -1)
452
453         def keyOK(self):
454                 ConfigListScreen.keyOK(self)
455                 try:
456                         from Screens.LocationBox import LocationBox
457                         sel = self["config"].getCurrent()[1]
458                         if sel == config.plugins.FanControl.LogPath:
459                                 self.session.openWithCallback(self.dirSelected, LocationBox, text = _("Choose path"), filename = "", currDir = self["config"].getCurrent()[1].value, minFree = 50)
460                 except Exception, e:
461                         self.session.open(MessageBox, "Error:\n" + str(e), MessageBox.TYPE_ERROR)
462
463         def dirSelected(self, dir):
464                 if dir is not None and dir != "?":
465                         if dir[-1:] != "/":
466                                 dir += "/"
467                         config.plugins.FanControl.LogPath.value = dir
468         
469         def cancel(self):
470                 global disableHDDread
471                 if config.plugins.FanControl.LogPath.value[-1:] != "/":
472                         config.plugins.FanControl.LogPath.value += "/"
473                 NeuStart = False
474                 if os.path.exists("/usr/lib/enigma2/python/Components/FanControl.py"):
475                         if not isDMMdisabled() and config.plugins.FanControl.DisableDMM.value:
476                                 disableDMM()
477                                 NeuStart = True
478                         if isDMMdisabled() and not config.plugins.FanControl.DisableDMM.value:
479                                 enableDMM()
480                                 NeuStart = True
481                 if config.plugins.FanControl.CheckHDDTemp.value == "auto" and config.plugins.FanControl.CheckHDDTemp.value != self.HDDmode:
482                         disableHDDread = True
483                 if config.plugins.FanControl.MonitorInExtension.value != self.MonitorMode:
484                         NeuStart = True
485
486                 for x in self["config"].list:
487                         x[1].save()
488
489                 if NeuStart:
490                         configfile.save()
491                         restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply the changes.\nDo you want to Restart the GUI now?"), MessageBox.TYPE_YESNO)
492                         restartbox.setTitle(_("Restart GUI now?"))
493                 else:
494                         self.close(False,self.session)
495
496         def selectionChanged(self):
497                 if not config.plugins.FanControl.EnableDataLog.value:
498                         return
499                 if config.plugins.FanControl.LogPath.value[-1:] != "/":
500                         config.plugins.FanControl.LogPath.value += "/"
501                 if not os.path.exists(config.plugins.FanControl.LogPath.value + "FC2data.csv") and Free(config.plugins.FanControl.LogPath.value):
502                         try:
503                                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","w")
504                                 try:
505                                         f.write(HeadLine)
506                                 except:
507                                         f.close()
508                         except IOError:
509                                 FClog("Data-Log-Error")
510
511         def restartGUI(self, answer):
512                 if answer is True:
513                         self.session.open(TryQuitMainloop, 3)
514                 else:
515                         self.close()
516
517 class FanControl2Plugin(ConfigListScreen,Screen):
518         skin = """
519                 <screen position="center,center" size="600,440" title="Fan Control 2">
520                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
521                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
522                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
523                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
524                         <ePixmap pixmap="skin_default/buttons/key_info.png" position="560,0" zPosition="4" size="35,25"  transparent="1" alphatest="on" />
525                         <ePixmap pixmap="skin_default/buttons/key_menu.png" position="560,20" zPosition="4" size="35,25"  transparent="1" alphatest="on" />
526                         <widget source="red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
527                         <widget source="green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
528                         <widget source="yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
529                         <widget source="blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
530                         <widget source="Version" render="Label" position="5,420" size="60,20" zPosition="1" font="Regular;11" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
531
532                         <widget name="config" position="10,50" size="580,200" scrollbarMode="showOnDemand" />
533                         <ePixmap position="20,260" size="560,3" pixmap="skin_default/div-h.png" transparent="1" alphatest="on" />
534                         <widget source="introduction" render="Label" position="5,262" size="580,30" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
535                         <ePixmap position="20,290" size="560,3" pixmap="skin_default/div-h.png" transparent="1" alphatest="on" />
536                         <widget source="TxtTemp" render="Label" position="5,330" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
537                         <widget source="TxtZielRPM" render="Label" position="5,350" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
538                         <widget source="TxtRPM" render="Label" position="5,370" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
539                         <widget source="TxtVLT" render="Label" position="5,390" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
540                         <widget source="TxtPWM" render="Label" position="5,410" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
541                         <widget source="PixTemp" render="Progress" position="210,340" size="375,5" borderWidth="1" />
542                         <widget source="PixZielRPM" render="Progress" position="210,360" size="375,5" borderWidth="1" />
543                         <widget source="PixRPM" render="Progress" position="210,380" size="375,5" borderWidth="1" />
544                         <widget source="PixVLT" render="Progress" position="210,400" size="375,5" borderWidth="1" />
545                         <widget source="PixPWM" render="Progress" position="210,420" size="375,5" borderWidth="1" />
546                 </screen>"""
547
548         def __init__(self, session, args = 0):
549                 global LastVLT
550                 global LastPWM
551                 self.session = session
552                 Screen.__init__(self, session)
553
554                 self.fan_timer = eTimer()
555                 self.fan_timer.callback.append(self.updateFanStatus)
556
557                 self.list = []
558                 self.list.append(getConfigListEntry(_("Fan type"), config.plugins.FanControl.Fan))
559                 self.list.append(getConfigListEntry(_("Fan off in Standby"), config.plugins.FanControl.StandbyOff))
560                 self.list.append(getConfigListEntry(_("min Speed rpm"), config.plugins.FanControl.minRPM))
561                 self.list.append(getConfigListEntry(_("max Speed rpm"), config.plugins.FanControl.maxRPM))
562                 self.list.append(getConfigListEntry(_("Static temp C"), config.plugins.FanControl.temp))
563                 self.list.append(getConfigListEntry(_("End temperature C"), config.plugins.FanControl.tempmax))
564                 self.list.append(getConfigListEntry(_("Initial Voltage"), config.plugins.FanControl.vlt))
565                 self.list.append(getConfigListEntry(_("Initial PWM"), config.plugins.FanControl.pwm))
566                 ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
567                 LastVLT = config.plugins.FanControl.vlt.value
568                 LastPWM = config.plugins.FanControl.pwm.value
569
570                 self["red"] = StaticText(_("Cancel"))
571                 self["green"] = StaticText(_("Save"))
572                 self["yellow"] = StaticText(_("Check"))
573                 self["blue"] = StaticText(_("Help"))
574                 self["introduction"] = StaticText()
575                 self["Version"] = StaticText(Version)
576                 self["TxtTemp"] = StaticText()
577                 self["TxtZielRPM"] = StaticText()
578                 self["TxtRPM"] = StaticText()
579                 self["TxtVLT"] = StaticText()
580                 self["TxtPWM"] = StaticText()
581                 self["PixTemp"] = Progress()
582                 self["PixZielRPM"] = Progress()
583                 self["PixRPM"] = Progress()
584                 self["PixVLT"] = Progress()
585                 self["PixPWM"] = Progress()
586
587                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "MenuActions", "EPGSelectActions"], 
588                 {
589                         "ok": self.save,
590                         "cancel": self.cancel,
591                         "red": self.cancel,
592                         "green": self.save,
593                         "yellow": self.pruefen,
594                         "blue": self.help,
595                         "menu": self.SetupMenu,
596                         "info": self.monitor
597                 }, -1)
598
599                 if not self.selectionChanged in self["config"].onSelectionChanged:
600                         self["config"].onSelectionChanged.append(self.selectionChanged)
601                 self.selectionChanged()
602                 self.onLayoutFinish.append(self.updateFanStatus)
603
604         def selectionChanged(self):
605                 global LastVLT
606                 global LastPWM
607                 global AktPWM
608                 global AktVLT
609                 global AktRPM
610                 self["introduction"].setText(_("Current value: %s") % (self.getCurrentValue()))
611                 if self["config"].getCurrentIndex() > 4:
612                         if LastVLT != config.plugins.FanControl.vlt.value or LastPWM !=config.plugins.FanControl.pwm.value:
613                                 LastVLT = config.plugins.FanControl.vlt.value
614                                 LastPWM = config.plugins.FanControl.pwm.value
615                                 AktVLT = LastVLT
616                                 AktPWM = LastPWM
617                                 id = 0
618                                 setVoltage(id,LastVLT)
619                                 setPWM(id,LastPWM)
620                                 AktRPM = GetFanRPM()
621                 d = config.plugins.FanControl.tempmax.value - config.plugins.FanControl.temp.value
622                 if d < 5:
623                         if config.plugins.FanControl.temp.value + d < 55:
624                                 config.plugins.FanControl.tempmax.value=config.plugins.FanControl.temp.value+5
625                         else:
626                                 config.plugins.FanControl.temp.value=config.plugins.FanControl.tempmax.value-5
627
628         def getCurrentValue(self):
629                 return str(self["config"].getCurrent()[1].getText())
630
631         def updateFanStatus(self):
632                 global ZielRPM
633                 global AktTemp
634                 global AktVLT
635                 global AktPWM
636                 global AktRPM
637                 if config.plugins.FanControl.Fan.value == "disabled":
638                         AktTemp = 0
639                         AktVLT = 0
640                         AktPWM = 0
641                         ZielRPM = 0
642                         AktRPM = 0
643                 self["TxtTemp"].setText(_("Temperature C  %4.1f") % (AktTemp))
644                 self["TxtZielRPM"].setText(_("Target rpm  %4d") % (ZielRPM))
645                 self["TxtRPM"].setText(_("Current rpm  %4d") % (AktRPM))
646                 self["TxtVLT"].setText(_("Voltage  %03d") % (AktVLT))
647                 self["TxtPWM"].setText(_("PWM  %03d") % (AktPWM))
648                 self["PixTemp"].value = int((AktTemp-config.plugins.FanControl.temp.value)*100/Test0(config.plugins.FanControl.tempmax.value-config.plugins.FanControl.temp.value))
649                 self["PixZielRPM"].value = int((ZielRPM-config.plugins.FanControl.minRPM.value)*100/Test0(config.plugins.FanControl.maxRPM.value-config.plugins.FanControl.minRPM.value))
650                 self["PixRPM"].value = int((AktRPM-config.plugins.FanControl.minRPM.value)*100/Test0(config.plugins.FanControl.maxRPM.value-config.plugins.FanControl.minRPM.value))
651                 self["PixVLT"].value = int(AktVLT/2.55)
652                 self["PixPWM"].value = int(AktPWM/2.55)
653                 self.fan_timer.start(2000, True)
654        
655         def save(self):
656                 for x in self["config"].list:
657                         x[1].save()
658                 self.close(True,self.session)
659
660         def cancel(self):
661                 for x in self["config"].list:
662                         x[1].cancel()
663                 self.close(False,self.session)
664
665         def pruefen(self):
666                 self.session.open(FanControl2Test)
667
668         def monitor(self):
669                 self.session.open(FanControl2Monitor)
670
671         def help(self):
672                 self.session.open(Console,_("Information"),["cat /usr/lib/enigma2/python/Plugins/Extensions/FanControl2/%s" % _("readme.txt")])
673
674         def SetupMenu(self):
675                 self.session.open(FanControl2SpezialSetup)
676
677 def DeleteData():
678         if config.plugins.FanControl.DeleteData.value == "0" or config.plugins.FanControl.EnableDataLog.value == False:
679                 return
680         try:
681                 FClog("Auto-Delete Data")
682                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","a")
683                 s = f.tell()
684                 f.close()
685                 if s < 150:
686                         return
687                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","r")
688                 f.seek(s-100)
689                 line = f.readline()
690                 line = f.readline()
691                 DT = line.split(";")
692                 DT = DT[0].split(" ")
693                 DD = DT[0].split(".")
694                 DD48h = datetime.date(int(DD[0]),int(DD[1]),int(DD[2])) - datetime.timedelta(int(config.plugins.FanControl.DeleteData.value))
695                 Dfind = "%04d.%02d.%02d %s" % (DD48h.year,DD48h.month,DD48h.day,DT[1])
696                 f.seek(0)
697                 line = f.readline()
698                 fw = open(config.plugins.FanControl.LogPath.value + "FC2data.csv.tmp","w")
699                 fw.write(HeadLine)
700                 for line in f.readlines():
701                         DT = line.split(";")
702                         if DT[0] > Dfind:
703                                 fw.write(line)
704                 f.close()
705                 fw.close()
706                 if os.path.exists(config.plugins.FanControl.LogPath.value + "FC2data.csv"):
707                         os.remove(config.plugins.FanControl.LogPath.value + "FC2data.csv")
708                 os.rename(config.plugins.FanControl.LogPath.value + "FC2data.csv.tmp",config.plugins.FanControl.LogPath.value + "FC2data.csv")
709         except Exception:
710                 FClog("Error Delete Data")
711
712 def getstatusoutput(cmd):
713         pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
714         text = pipe.read()
715         sts = pipe.close()
716         if sts is None: sts = 0
717         if text[-1:] == '\n': text = text[:-1]
718         return sts, text
719
720 def HDDtestTemp():
721         global disableHDDread
722         if harddiskmanager.HDDCount() > 0 and config.plugins.FanControl.CheckHDDTemp.value !="never":
723                 disableHDDread = False
724                 for hdd in harddiskmanager.HDDList():
725                         FClog("%s %s Mode:%s" % (hdd[1].model(), hdd[1].getDeviceName(), config.plugins.FanControl.CheckHDDTemp.value))
726                         if config.plugins.FanControl.CheckHDDTemp.value == "auto":
727                                 (stat,wert)=getstatusoutput("hdparm -y %s" % hdd[1].getDeviceName())
728                                 time.sleep(0.5)
729                                 (stat,wert)=ReadHDDtemp(hdd[1].getDeviceName())
730                                 if stat != 0:
731                                         (stat,wert)=getstatusoutput("smartctl --smart=on %s" % hdd[1].getDeviceName())
732                                         FClog("HDD Temperature not readable")
733                                 time.sleep(0.5)
734                                 (stat,wert)=getstatusoutput("hdparm -C %s" % hdd[1].getDeviceName())
735                                 if wert.find("standby")>0:
736                                         FClog("HDD supports Temp reading without Spinup")
737                                 else:
738                                         if hdd[1].isSleeping():
739                                                 (stat,wert)=getstatusoutput("hdparm -y %s" % hdd[1].getDeviceName())
740                                         FClog("HDD not supports Temp reading without Spinup -> Disabled")
741                                         disableHDDread = True
742
743 def ReadHDDtemp(D):
744         return getstatusoutput("smartctl -A %s | grep \"194 Temp\" | grep Always" % D)
745
746 def GetHDDtemp(OneTime):
747         global AktHDD
748         AktHDD = []
749         if harddiskmanager.HDDCount() > 0 and config.plugins.FanControl.CheckHDDTemp.value != "never" or OneTime == True:
750                 for hdd in harddiskmanager.HDDList():
751                         sleeptime = int((time.time() - hdd[1].last_access))
752 #                       FClog("HDD Temp reading %s %s %ds %s" % (config.plugins.FanControl.CheckHDDTemp.value, disableHDDread, sleeptime, hdd[1].isSleeping()))
753                         if config.plugins.FanControl.CheckHDDTemp.value == "true" or (config.plugins.FanControl.CheckHDDTemp.value == "auto" and not disableHDDread) or ((not hdd[1].isSleeping()) and sleeptime < 120) or OneTime == True:
754                                 (stat,wert)=ReadHDDtemp(hdd[1].getDeviceName())
755                                 if stat == 0:
756                                         try:
757                                                 AktHDD.append(int(wert[wert.find("Always")+6:].replace(" ","").replace("-","")[:2]))
758                                         except:
759                                                 AktHDD.append(0)
760                                 if len(AktHDD) == 0:
761                                         AktHDD = [0]
762                                 FClog("HDD Temp %dC" % (AktHDD[-1]))
763         if len(AktHDD) == 0:
764                 AktHDD = [0]
765         return
766
767 def HDDsSleeping(): 
768         for hdd in harddiskmanager.HDDList():
769                 if not hdd[1].isSleeping():
770                         return False
771         return True
772
773 def FC2systemStatus():
774         S = int(FC2werte[5])
775         R = " -" if S>0 else " "
776         if (S & 1)>0 :
777                 R += " BoxOn"
778         if (S & 2)>0 :
779                 R += " HDDon"
780         if (S & 4)>0 :
781                 R += " REC"
782         return R
783
784 class FanControl2(Screen):
785         skin = """ <screen position="100,100" size="300,300" title="FanControl2" > </screen>"""
786
787         def __init__(self,session):
788                 global Box
789                 Screen.__init__(self,session)
790                 self.session = session
791                 self.FanMin     = 500
792                 self.FanMax     = 1500
793                 self.targetTemp = 50.0
794                 self.maxTemp    = 55.0
795                 self.Range      = 5
796                 self.Fan        = "aus"
797                 self.dontshutdown = False
798                 FClog("Starting up")
799                 if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data/diagram.class.org"):
800                         os.rename("/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data/diagram.class.org","/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data/diagram.class")
801                 if not isDMMdisabled() and config.plugins.FanControl.DisableDMM.value:
802                         disableDMM()
803                 Box = GetBox()
804                 HDDtestTemp()
805                 GetHDDtemp(False)
806                 DeleteData()
807                 self.timer = eTimer()
808                 if self.query not in self.timer.callback:
809                         self.timer.callback.append(self.query)
810                 self.timer.startLongTimer(10)
811                 config.misc.standbyCounter.addNotifier(self.standbyQuery, initial_call = False)
812
813         def FC2AskShutdown(self):
814                 if not self.dontshutdown:
815                         self.dontshutdown = True
816                         self.session.openWithCallback(self.FC2DoShutdown, MessageBox, _("FanControl2 emergency, Box Shutdown now?"),type = MessageBox.TYPE_YESNO,timeout = 60)
817
818         def FC2DoShutdown(self,retval):
819                 if (retval):
820                         if Standby.inTryQuitMainloop == False:
821                                 self.session.open(Standby.TryQuitMainloop, 1)
822
823         def stop(self):
824                 FClog("Stop")
825                 if self.query in self.timer.callback:
826                         self.timer.callback.remove(self.query)
827                 self.timer.stop()
828
829         def CurrTemp(self):
830                 m1 = 0.1
831                 m2 = 0.1
832                 ti = [0,0,0,0,0,0,0,0,0,0]
833                 templist = sensors.getSensorsList(sensors.TYPE_TEMPERATURE)
834                 tempcount = len(templist)
835                 for count in range(tempcount):
836                         tt = sensors.getSensorValue(count)
837                         ti[count] = tt
838                         if m1 < tt:
839                                 mi = count
840                                 m1 = tt
841                 for count in range(tempcount):
842                         if m2 < ti[count] and count != mi:
843                                 m2 = ti[count]
844                 if m2 == 0.1:
845                         m2 = m1
846                 return (m1 + m2) / 2.0
847                 
848         def cycle(self):
849                 self.Range = self.maxTemp - self.targetTemp
850                 x = AktTemp - self.targetTemp
851                 rpm = skal(x, 0, self.Range, self.FanMin, self.FanMax)
852                 return rpm
853
854         def standbyQuery(self, configElement):
855                 Standby.inStandby.onClose.append(self.query)
856                 self.query()
857                 
858         def query(self):
859                 global FirstStart
860                 global istStandbySave
861                 global Overheat
862                 global OverheatTimer
863                 global FanOffWait
864                 global RPMread
865                 global RPMdiff
866                 global FanFehler            
867                 global ZielRPM
868                 global AktRPM
869                 global AktTemp
870                 global AktVLT
871                 global AktPWM
872                 global Recording
873 #               tt = time.time()
874                 try:
875                         if config.plugins.FanControl.Fan.value == "disabled":
876                                 self.timer.startLongTimer(10)
877                                 return
878                         self.targetTemp = config.plugins.FanControl.temp.value
879                         self.maxTemp    = config.plugins.FanControl.tempmax.value
880                         self.Fan        = config.plugins.FanControl.Fan.value
881                         self.Vlt        = config.plugins.FanControl.vlt.value
882                         self.HDDidle    = True
883                         id = 0
884                         AktRPMtmp = 0
885                         sleeptime = 0
886                         AktTemp = self.CurrTemp()
887                         Recording = self.session.nav.RecordTimer.isRecording()
888                         if AktTemp >= config.plugins.FanControl.ShutdownTemp.value:
889                                 FClog("Emergency Shutdown")
890                                 self.FC2AskShutdown()
891                         if harddiskmanager.HDDCount() > 0:
892                                 self.HDDidle = HDDsSleeping()
893                                 if int(strftime("%S")) < 10 and strftime("%M")[-1:] == "0":
894                                         GetHDDtemp(False)
895                                         if strftime("%H:%M") == "00:00":
896                                                 DeleteData()
897                         S=0
898                         if not Standby.inStandby:
899                                 S+=1
900                         if not self.HDDidle:
901                                 S+=2
902                         if Recording:
903                                 S+=4
904                         FC2werte[5]=str(S)
905
906                         if (Standby.inStandby) and (not Overheat) and ((config.plugins.FanControl.StandbyOff.value == "true") or ((config.plugins.FanControl.StandbyOff.value == "trueRec") and (not Recording and self.HDDidle))):
907                                 FClog("Fan Off Temp: %d %s" % (AktTemp,FC2systemStatus()))
908                                 setVoltage(id,0)
909                                 setPWM(id,0)
910                                 FC2werte[0] = AktTemp
911                                 FC2werte[1] = 0
912                                 FC2werte[2] = 0
913                                 FC2werte[3] = 0
914 #                               FC2werte[4] = str(AktHDD)[1:-1].replace(",","")
915                                 FC2werte[4] = max(AktHDD) if len(AktHDD) > 0 else 0
916                                 FCdata()
917                                 FirstStart = True
918                                 OverheatTemp = self.maxTemp + config.plugins.FanControl.AddOverheat.value
919                                 OverheatTimer = 0
920                                 FanOffWait = True
921                                 if OverheatTemp > 65:
922                                         OverheatTemp = 65
923                                 if AktTemp > OverheatTemp:
924                                         Overheat = True
925                                         FClog("Overheat")
926                         else:
927                                 if (Overheat and AktTemp < self.maxTemp-3) or not Standby.inStandby:
928                                         Overheat = False
929                                 AktVLTtmp = getVoltage(id)
930                                 if Standby.inStandby and Standby.inStandby == istStandbySave and RPMdiff == 1:
931                                         tmp = GetFanRPM()
932                                         RPMdiff = AktRPM-tmp
933                                         if RPMdiff < 150 or tmp < 300 or self.Fan == "3pin":
934                                                 RPMdiff = 0
935                                         else:
936                                                 if config.plugins.FanControl.minRPM.value - RPMdiff < 300:
937                                                         RPMdiff = config.plugins.FanControl.minRPM.value - 300
938                                                 FClog("RPM-Range shifted -%drpm" % RPMdiff)
939                                 if not Standby.inStandby:
940                                         RPMdiff = 0
941                                 self.FanMin = config.plugins.FanControl.minRPM.value - RPMdiff
942                                 self.FanMax = config.plugins.FanControl.maxRPM.value - RPMdiff
943                                 if Standby.inStandby != istStandbySave or AktVLT != AktVLTtmp:
944                                         istStandbySave = Standby.inStandby
945                                         AktVLTtmp = AktVLT
946                                         setVoltage(id,AktVLT)
947                                         setPWM(id,AktPWM)
948                                         RPMdiff = 1
949                                         FClog("Fan Reset")
950                                 if (AktVLT + AktPWM) == 0:
951                                         FirstStart = True
952                                 if FirstStart == True:
953                                         FirstStart = False
954                                         AktVLTtmp = self.Vlt
955                                         setVoltage(id,self.Vlt)
956                                         setPWM(id,config.plugins.FanControl.pwm.value)
957                                 AktRPMtmp = GetFanRPM()
958                                 if RPMread>0 and RPMread<3:
959                                         self.timer.start(400, True)
960                                         return
961                                 AktRPM = AktRPMtmp
962                                 AktVLT = AktVLTtmp
963                                 AktPWM = getPWM(id)
964                                 FClog("Vlt:%d Pwm:%d Fan:%s  %s" % (AktVLT,AktPWM,self.Fan,FC2systemStatus()))
965                                 FC2werte[0] = AktTemp
966                                 FC2werte[1] = AktRPM
967                                 FC2werte[2] = AktVLT
968                                 FC2werte[3] = AktPWM
969                                 FC2werte[4] = max(AktHDD) if len(AktHDD) > 0 else 0
970                                 FCdata()
971                                 if int(strftime("%M")) == 0:
972                                         FC2stunde[int(strftime("%H"))] = "%4.1f<BR>%d" % (AktTemp,AktRPM)
973                                 RPMread = 0
974                                 ZielRPM = self.cycle()
975                                 if (FanOffWait and OverheatTimer < 30) or (Overheat and OverheatTimer < 60):
976                                         ZielRPM = self.FanMin
977                                         OverheatTimer += 1
978                                         FClog("FanStartTimeout set MinRPM (%d)" % (OverheatTimer)) 
979                                 else:
980                                         FanOffWait = False
981                                 FClog(_("currentRPM:%d targetRPM:%d Temp:%4.1f") % (AktRPM,ZielRPM,AktTemp))
982                                 if ZielRPM > 0 and AktRPM == 0:
983                                         FanFehler += 1
984                                         if FanFehler > 90:
985                                                 FanFehler -= 18
986                                                 FClog("Fan Error")
987                                                 if config.plugins.FanControl.ShowError.value == "true":
988                                                         Notifications.AddNotification(MessageBox, _("Fan is not working!"), type=MessageBox.TYPE_INFO, timeout=5)
989                                                 if config.plugins.FanControl.ShowError.value == "shutdown":
990                                                         self.FC2AskShutdown()
991                                 else:
992                                         FanFehler = 0
993                                 if self.Fan == "4pin":
994                                         if AktPWM < 255 and AktPWM > 0 and AktVLT != self.Vlt:
995                                                 AktVLT = (AktVLT-1 if AktVLT > self.Vlt else AktVLT+1)
996                                                 setVoltage(id,AktVLT)
997                                         if AktRPM+29 < ZielRPM:
998                                                 AktPWM = (AktPWM+5 if ZielRPM-AktRPM > 100 else AktPWM+1)
999                                                 setPWM(id,AktPWM)
1000                                                 if AktPWM >= 255 and AktVLT < 255:
1001                                                         AktVLT += 1
1002                                                         setVoltage(id,AktVLT)
1003                                         elif AktRPM-19 > ZielRPM:
1004                                                 AktPWM = (AktPWM-5 if AktRPM-ZielRPM > 100 else AktPWM-1)
1005                                                 setPWM(id,AktPWM)
1006 # 4
1007                                                 if AktPWM < 0 and AktVLT > 5:
1008                                                         AktVLT -= 1
1009                                                         setVoltage(id,AktVLT)
1010                                         if AktVLT > self.Vlt:
1011                                                 AktPWM = 256
1012                                         if AktPWM < 0:
1013                                                 AktPWM = 0
1014                                 elif self.Fan == "3pin":
1015                                         if AktRPM+29 < ZielRPM:
1016                                                 AktVLT = (AktVLT+5 if ZielRPM-AktRPM > 100 else AktVLT+1)
1017                                                 setVoltage(id,AktVLT)
1018                                         elif AktRPM-19 > ZielRPM:
1019                                                 AktVLT = (AktVLT-5 if AktRPM-ZielRPM > 100 else AktVLT-1)
1020                                                 setVoltage(id,AktVLT)
1021
1022                 except Exception:
1023                         FClog("Control Error")
1024                         import traceback, sys
1025                         traceback.print_exc(file=sys.stdout)
1026 #               FClog(str(time.time() - tt ))
1027                 self.timer.startLongTimer(10)
1028
1029 def autostart(reason, **kwargs):
1030         global session
1031         from Plugins.Extensions.WebInterface.WebChilds.Toplevel import addExternalChild
1032         from FC2webSite import FC2web, FC2webLog, FC2webChart
1033         from twisted.web import static
1034         root = static.File("/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data")
1035 #       root = FC2web()
1036         root.putChild("", FC2web())
1037         root.putChild("log", FC2webLog())
1038         root.putChild("chart", FC2webChart())
1039         addExternalChild( ("fancontrol", root) )
1040         if reason == 0 and kwargs.has_key("session"):
1041                 session = kwargs["session"]
1042                 session.open(FanControl2)
1043           
1044 def Plugins(**kwargs):
1045         list = [
1046         PluginDescriptor(name="Fan Control", 
1047         description="Fan Control 2", 
1048         where = [PluginDescriptor.WHERE_SESSIONSTART, 
1049         PluginDescriptor.WHERE_AUTOSTART], 
1050         fnc = autostart),
1051         PluginDescriptor(name="Fan Control", 
1052         description="Fan Control 2", 
1053         where = PluginDescriptor.WHERE_PLUGINMENU,
1054         icon = "plugin.png",
1055         fnc = main)]
1056         if config.plugins.FanControl.MonitorInExtension.value:
1057                 list.append(PluginDescriptor(
1058                 name="Fan Control 2 - Monitor", 
1059                 description="Fan Control 2", 
1060                 where = PluginDescriptor.WHERE_EXTENSIONSMENU,
1061                 icon = "plugin.png",
1062                 fnc = mainMonitor))
1063         return list