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