[FanControl2] Fix: Crash because of changes in HDD management
[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.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 #Configuration
132 config.plugins.FanControl = ConfigSubsection()
133 config.plugins.FanControl.Fan = ConfigSelection(choices = [("disabled", _("disabled")), ("aus", _("Control disabled")), ("3pin", _("3Pin")), ("4pin", _("4Pin"))], default = "disabled")
134 config.plugins.FanControl.StandbyOff = ConfigSelection(choices = [("false", _("no")), ("true", _("yes")), ("trueRec", _("yes, Except for Recording or HDD"))], default="false")
135 config.plugins.FanControl.minRPM = ConfigSlider(default = 600, increment = 50, limits = (0, 1500))
136 config.plugins.FanControl.maxRPM = ConfigSlider(default = 3000, increment = 50, limits = (500, 6000))
137 config.plugins.FanControl.temp = ConfigSlider(default = 40, increment = 1, limits = (30, 50))
138 config.plugins.FanControl.tempmax = ConfigSlider(default = 50, increment = 1, limits = (35, 55))
139 config.plugins.FanControl.pwm = ConfigSlider(default = 130, increment = 5, limits = (0, 255))
140 config.plugins.FanControl.vlt = ConfigSlider(default = 255, increment = 5, limits = (0, 255))
141 config.plugins.FanControl.ShowError = ConfigSelection(choices = [("false", _("do nothing")), ("true", _("display Info")), ("shutdown", _("Box Shutdown"))], default="true")
142 config.plugins.FanControl.ShutdownTemp = ConfigInteger(default = 65,limits = (50, 80))
143 config.plugins.FanControl.AddOverheat = ConfigInteger(default = 0,limits = (0, 9))
144 config.plugins.FanControl.DisableDMM = ConfigYesNo(default = False)
145 config.plugins.FanControl.LogCount = ConfigInteger(default = 40,limits = (40, 999))
146 config.plugins.FanControl.LogPath = ConfigText(default="/tmp/", fixed_size=False)
147 config.plugins.FanControl.DeleteData = ConfigSelection(choices = [("0", _("no")), ("2", "2"), ("3", "3"), ("7", "7"), ("14", "14"), ("30", "30")], default="14")
148 config.plugins.FanControl.EnableDataLog = ConfigYesNo(default = False)
149 config.plugins.FanControl.EnableEventLog = ConfigYesNo(default = False)
150 config.plugins.FanControl.CheckHDDTemp = ConfigSelection(choices = [("false", _("no")), ("true", _("yes")), ("auto", _("auto")), ("never", _("never"))], default="auto")
151 config.plugins.FanControl.MonitorInExtension = ConfigYesNo(default = True)
152 config.plugins.FanControl.FanControlInExtension = 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         value = int(value / int(config.plugins.FanControl.Multi.value))
161         if value > 0 and value < 6000:
162                 RPMread = 0
163         else:
164                 RPMread += 1
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                 elif 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                 else:
326                         self["TextTest1"].setText(_("please set fan type (3Pin or 4Pin)"))
327
328                 setVoltage(self.id,SaveAktVLT)
329                 setPWM(self.id,SaveAktPWM)
330                 config.plugins.FanControl.Fan.value = SaveFan
331
332         def cancel(self):
333                 self.close(False,self.session)
334
335 class FanControl2Monitor(Screen, ConfigListScreen):
336         skin = """
337                 <screen position="center,center" size="600,260" title="Fan Control 2 - Monitor">
338
339                         <widget source="TxtTemp0" render="Label" position="5,30" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
340                         <widget source="TxtTemp1" render="Label" position="5,50" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
341                         <widget source="TxtTemp2" render="Label" position="5,70" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
342                         <widget source="TxtTemp3" render="Label" position="5,90" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
343                         <widget source="TxtTemp4" render="Label" position="5,110" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
344                         <widget source="TxtTemp5" render="Label" position="5,130" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
345                         <widget source="TxtTemp6" render="Label" position="5,150" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
346                         <widget source="TxtTemp7" render="Label" position="5,170" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
347                         <widget source="TxtHDD" render="Label" position="5,190" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
348                         <widget source="TxtFan" render="Label" position="5,210" size="250,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
349                         <widget name="TxtMinTemp" position="260,20" size="50,12" zPosition="1" font="Regular;12" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
350                         <widget source="TxtFC2Temp" render="Label" position="398,20" size="50,12" zPosition="1" font="Regular;17" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
351                         <widget name="TxtMaxTemp" position="535,20" size="50,12" zPosition="1" font="Regular;12" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
352                         <widget source="ProTemp0" render="Progress" position="260,40" size="325,5" borderWidth="1" />
353                         <widget source="ProTemp1" render="Progress" position="260,60" size="325,5" borderWidth="1" />
354                         <widget source="ProTemp2" render="Progress" position="260,80" size="325,5" borderWidth="1" />
355                         <widget source="ProTemp3" render="Progress" position="260,100" size="325,5" borderWidth="1" />
356                         <widget source="ProTemp4" render="Progress" position="260,120" size="325,5" borderWidth="1" />
357                         <widget source="ProTemp5" render="Progress" position="260,140" size="325,5" borderWidth="1" />
358                         <widget source="ProTemp6" render="Progress" position="260,160" size="325,5" borderWidth="1" />
359                         <widget source="ProTemp7" render="Progress" position="260,180" size="325,5" borderWidth="1" />
360                         <widget source="ProHDD" render="Progress" position="260,200" size="325,5" borderWidth="1" />
361                         <widget source="ProFan" render="Progress" position="260,220" size="325,5" borderWidth="1" />
362
363                 </screen>"""
364         
365         def __init__(self, session, args = None):
366                 Screen.__init__(self, session)
367
368                 self.temp_timer = eTimer()
369                 self.temp_timer.callback.append(self.updateTemp)
370
371                 for count in range(8):
372                         self["ProTemp%d" % count] = Progress()
373                         self["TxtTemp%d" % count] = StaticText("")
374                 self["ProHDD"] = Progress()
375                 self["TxtHDD"] = StaticText("")
376                 self["ProFan"] = Progress()
377                 self["TxtFan"] = StaticText("")
378                 self["TxtFC2Temp"] = StaticText("")
379                 self["TxtMinTemp"] = Label("30")
380                 self["TxtMaxTemp"] = Label("55")
381
382                 self["actions"] = ActionMap(["OkCancelActions", "EPGSelectActions"], 
383                 {
384                         "ok": self.cancel,
385                         "cancel": self.cancel,
386                         "info": self.getHDD
387                 }, -1)
388
389                 self.onLayoutFinish.append(self.updateTemp)
390
391         def updateTemp(self):
392                 templist = sensors.getSensorsList(sensors.TYPE_TEMPERATURE)
393                 tempcount = len(templist)
394                 for count in range(tempcount):
395                         tt = sensors.getSensorValue(count)
396                         self["ProTemp%d" % count].value = int((tt-30)*100/(55-30)) 
397                         if sensors.getSensorName(count) == "undefined":
398                                 self["TxtTemp%d" % count].setText(_("%s   %02d C") % (TempName[count], tt))
399                         else:
400                                 self["TxtTemp%d" % count].setText(_("%s   %02d C") % (sensors.getSensorName(count), tt))
401                 if harddiskmanager.HDDCount() > 0:
402                         if max(AktHDD) > 0:
403                                 self["ProHDD"].value = int((max(AktHDD)-30)*100/(55-30)) 
404                                 self["TxtHDD"].setText(_("%s   %02d C") % ("HDD", max(AktHDD)))
405                         elif config.plugins.FanControl.CheckHDDTemp.value !="never":
406                                 self["TxtHDD"].setText(_("press Info for HDD-Temp"))
407                 self["TxtFan"].setText(_("Current rpm  %4d") % (AktRPM))
408                 self["ProFan"].value = int((AktRPM-config.plugins.FanControl.minRPM.value)*100/Test0(config.plugins.FanControl.maxRPM.value-config.plugins.FanControl.minRPM.value))
409                 if tempcount>1:
410                         self["TxtFC2Temp"].setText("%4.1f" % AktTemp)
411                 self.temp_timer.start(2000, True)
412         
413         def cancel(self):
414                 self.close(False,self.session)
415
416         def getHDD(self):
417                 if harddiskmanager.HDDCount() > 0 and config.plugins.FanControl.CheckHDDTemp.value !="never":
418                         GetHDDtemp(True)
419                         for hdd in harddiskmanager.HDDList():
420                                 if hdd[1].model().startswith("ATA"):
421                                         if hdd[1].isSleeping():
422                                                 (stat,wert)=getstatusoutput("hdparm -y %s" % hdd[1].getDeviceName())
423
424 class FanControl2SpezialSetup(Screen, ConfigListScreen):
425         skin = """
426                 <screen position="center,center" size="600,380" title="Fan Control 2 - Setup" >
427                         <widget name="config" position="10,20" size="580,350" scrollbarMode="showOnDemand" />
428                 </screen>"""
429
430         def __init__(self, session, args = None):
431                 Screen.__init__(self, session)
432
433                 config.plugins.FanControl.DisableDMM.value = isDMMdisabled()
434                 self.HDDmode = config.plugins.FanControl.CheckHDDTemp.value
435                 self.MonitorMode = config.plugins.FanControl.MonitorInExtension.value
436                 self.FanControlMode = config.plugins.FanControl.FanControlInExtension.value
437
438                 self.list = []
439                 self.list.append(getConfigListEntry(_("Action in case of Fan failure"), config.plugins.FanControl.ShowError))
440                 self.list.append(getConfigListEntry(_("Box shutdown at Temperature (C)"), config.plugins.FanControl.ShutdownTemp))
441                 self.list.append(getConfigListEntry(_("increases overheating protection to (C)"), config.plugins.FanControl.AddOverheat))
442                 self.list.append(getConfigListEntry(_("read HDD-Temperature in HDD-Standby-Mode"), config.plugins.FanControl.CheckHDDTemp))
443                 self.list.append(getConfigListEntry(_("disable DMM-FanControl"), config.plugins.FanControl.DisableDMM))
444                 self.list.append(getConfigListEntry(_("Show Fan Speed as"), config.plugins.FanControl.Multi))
445                 self.list.append(getConfigListEntry(_("Show Plugin in Extension-Menu"), config.plugins.FanControl.FanControlInExtension))
446                 self.list.append(getConfigListEntry(_("Show Monitor in Extension-Menu"), config.plugins.FanControl.MonitorInExtension))
447                 self.list.append(getConfigListEntry(_("Number of WebIF-Log-Entries"), config.plugins.FanControl.LogCount))
448                 self.list.append(getConfigListEntry(_("Logging path"), config.plugins.FanControl.LogPath))
449                 self.list.append(getConfigListEntry(_("Enable Data Logging"), config.plugins.FanControl.EnableDataLog))
450                 self.list.append(getConfigListEntry(_("Auto-Delete Data older than (Days)"), config.plugins.FanControl.DeleteData))
451                 self.list.append(getConfigListEntry(_("Enable Event Logging"), config.plugins.FanControl.EnableEventLog))
452                 ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
453
454                 self["actions"] = ActionMap(["OkCancelActions"], 
455                 {
456                         "ok": self.keyOK,
457                         "cancel": self.cancel
458                 }, -1)
459
460         def keyOK(self):
461                 ConfigListScreen.keyOK(self)
462                 try:
463                         from Screens.LocationBox import LocationBox
464                         sel = self["config"].getCurrent()[1]
465                         if sel == config.plugins.FanControl.LogPath:
466                                 self.session.openWithCallback(self.dirSelected, LocationBox, text = _("Choose path"), filename = "", currDir = self["config"].getCurrent()[1].value, minFree = 50)
467                 except Exception, e:
468                         self.session.open(MessageBox, "Error:\n" + str(e), MessageBox.TYPE_ERROR)
469
470         def dirSelected(self, dir):
471                 if dir is not None and dir != "?":
472                         if dir[-1:] != "/":
473                                 dir += "/"
474                         config.plugins.FanControl.LogPath.value = dir
475         
476         def cancel(self):
477                 global disableHDDread
478                 if config.plugins.FanControl.LogPath.value[-1:] != "/":
479                         config.plugins.FanControl.LogPath.value += "/"
480                 NeuStart = False
481                 if os.path.exists("/usr/lib/enigma2/python/Components/FanControl.py"):
482                         if not isDMMdisabled() and config.plugins.FanControl.DisableDMM.value:
483                                 disableDMM()
484                                 NeuStart = True
485                         if isDMMdisabled() and not config.plugins.FanControl.DisableDMM.value:
486                                 enableDMM()
487                                 NeuStart = True
488                 if config.plugins.FanControl.CheckHDDTemp.value == "auto" and config.plugins.FanControl.CheckHDDTemp.value != self.HDDmode:
489                         disableHDDread = True
490                 if config.plugins.FanControl.MonitorInExtension.value != self.MonitorMode:
491                         NeuStart = True
492                 if config.plugins.FanControl.FanControlInExtension.value != self.FanControlMode:
493                         NeuStart = True
494
495                 for x in self["config"].list:
496                         x[1].save()
497
498                 if NeuStart:
499                         configfile.save()
500                         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)
501                         restartbox.setTitle(_("Restart GUI now?"))
502                 else:
503                         self.close(False,self.session)
504
505         def selectionChanged(self):
506                 if not config.plugins.FanControl.EnableDataLog.value:
507                         return
508                 if config.plugins.FanControl.LogPath.value[-1:] != "/":
509                         config.plugins.FanControl.LogPath.value += "/"
510                 if not os.path.exists(config.plugins.FanControl.LogPath.value + "FC2data.csv") and Free(config.plugins.FanControl.LogPath.value):
511                         try:
512                                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","w")
513                                 try:
514                                         f.write(HeadLine)
515                                 except:
516                                         f.close()
517                         except IOError:
518                                 FClog("Data-Log-Error")
519
520         def restartGUI(self, answer):
521                 if answer is True:
522                         self.session.open(TryQuitMainloop, 3)
523                 else:
524                         self.close()
525
526 class FanControl2Plugin(ConfigListScreen,Screen):
527         skin = """
528                 <screen position="center,center" size="600,440" title="Fan Control 2">
529                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
530                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
531                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
532                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
533                         <ePixmap pixmap="skin_default/buttons/key_info.png" position="560,0" zPosition="4" size="35,25"  transparent="1" alphatest="on" />
534                         <ePixmap pixmap="skin_default/buttons/key_menu.png" position="560,20" zPosition="4" size="35,25"  transparent="1" alphatest="on" />
535                         <widget source="red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
536                         <widget source="green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
537                         <widget source="yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
538                         <widget source="blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
539                         <widget source="Version" render="Label" position="5,420" size="60,20" zPosition="1" font="Regular;11" halign="left" valign="center" backgroundColor="#25062748" transparent="1" />
540
541                         <widget name="config" position="10,50" size="580,200" scrollbarMode="showOnDemand" />
542                         <ePixmap position="20,260" size="560,3" pixmap="skin_default/div-h.png" transparent="1" alphatest="on" />
543                         <widget source="introduction" render="Label" position="5,262" size="580,30" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
544                         <ePixmap position="20,290" size="560,3" pixmap="skin_default/div-h.png" transparent="1" alphatest="on" />
545                         <widget source="TxtTemp" render="Label" position="5,330" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
546                         <widget source="TxtZielRPM" render="Label" position="5,350" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
547                         <widget source="TxtRPM" render="Label" position="5,370" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
548                         <widget source="TxtVLT" render="Label" position="5,390" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
549                         <widget source="TxtPWM" render="Label" position="5,410" size="200,25" zPosition="1" font="Regular;17" halign="right" valign="center" backgroundColor="#25062748" transparent="1" />
550                         <widget source="PixTemp" render="Progress" position="210,340" size="375,5" borderWidth="1" />
551                         <widget source="PixZielRPM" render="Progress" position="210,360" size="375,5" borderWidth="1" />
552                         <widget source="PixRPM" render="Progress" position="210,380" size="375,5" borderWidth="1" />
553                         <widget source="PixVLT" render="Progress" position="210,400" size="375,5" borderWidth="1" />
554                         <widget source="PixPWM" render="Progress" position="210,420" size="375,5" borderWidth="1" />
555                 </screen>"""
556
557         def __init__(self, session, args = 0):
558                 global LastVLT
559                 global LastPWM
560                 self.session = session
561                 Screen.__init__(self, session)
562
563                 self.fan_timer = eTimer()
564                 self.fan_timer.callback.append(self.updateFanStatus)
565
566                 self.list = []
567                 self.list.append(getConfigListEntry(_("Fan type"), config.plugins.FanControl.Fan))
568                 self.list.append(getConfigListEntry(_("Fan off in Standby"), config.plugins.FanControl.StandbyOff))
569                 self.list.append(getConfigListEntry(_("min Speed rpm"), config.plugins.FanControl.minRPM))
570                 self.list.append(getConfigListEntry(_("max Speed rpm"), config.plugins.FanControl.maxRPM))
571                 self.list.append(getConfigListEntry(_("Static temp C"), config.plugins.FanControl.temp))
572                 self.list.append(getConfigListEntry(_("End temperature C"), config.plugins.FanControl.tempmax))
573                 self.list.append(getConfigListEntry(_("Initial Voltage"), config.plugins.FanControl.vlt))
574                 self.list.append(getConfigListEntry(_("Initial PWM"), config.plugins.FanControl.pwm))
575                 ConfigListScreen.__init__(self, self.list, session = self.session, on_change = self.selectionChanged)
576                 LastVLT = config.plugins.FanControl.vlt.value
577                 LastPWM = config.plugins.FanControl.pwm.value
578
579                 self["red"] = StaticText(_("Cancel"))
580                 self["green"] = StaticText(_("Save"))
581                 self["yellow"] = StaticText(_("Check"))
582                 self["blue"] = StaticText(_("Help"))
583                 self["introduction"] = StaticText()
584                 self["Version"] = StaticText(Version)
585                 self["TxtTemp"] = StaticText()
586                 self["TxtZielRPM"] = StaticText()
587                 self["TxtRPM"] = StaticText()
588                 self["TxtVLT"] = StaticText()
589                 self["TxtPWM"] = StaticText()
590                 self["PixTemp"] = Progress()
591                 self["PixZielRPM"] = Progress()
592                 self["PixRPM"] = Progress()
593                 self["PixVLT"] = Progress()
594                 self["PixPWM"] = Progress()
595
596                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "MenuActions", "EPGSelectActions"], 
597                 {
598                         "ok": self.save,
599                         "cancel": self.cancel,
600                         "red": self.cancel,
601                         "green": self.save,
602                         "yellow": self.pruefen,
603                         "blue": self.help,
604                         "menu": self.SetupMenu,
605                         "info": self.monitor
606                 }, -1)
607
608                 if not self.selectionChanged in self["config"].onSelectionChanged:
609                         self["config"].onSelectionChanged.append(self.selectionChanged)
610                 self.selectionChanged()
611                 self.onLayoutFinish.append(self.updateFanStatus)
612
613         def selectionChanged(self):
614                 global LastVLT
615                 global LastPWM
616                 global AktPWM
617                 global AktVLT
618                 global AktRPM
619                 self["introduction"].setText(_("Current value: %s") % (self.getCurrentValue()))
620                 if self["config"].getCurrentIndex() > 4:
621                         if LastVLT != config.plugins.FanControl.vlt.value or LastPWM !=config.plugins.FanControl.pwm.value:
622                                 LastVLT = config.plugins.FanControl.vlt.value
623                                 LastPWM = config.plugins.FanControl.pwm.value
624                                 AktVLT = LastVLT
625                                 AktPWM = LastPWM
626                                 id = 0
627                                 setVoltage(id,LastVLT)
628                                 setPWM(id,LastPWM)
629                                 AktRPM = GetFanRPM()
630                 d = config.plugins.FanControl.tempmax.value - config.plugins.FanControl.temp.value
631                 if d < 5:
632                         if config.plugins.FanControl.temp.value + d < 55:
633                                 config.plugins.FanControl.tempmax.value=config.plugins.FanControl.temp.value+5
634                         else:
635                                 config.plugins.FanControl.temp.value=config.plugins.FanControl.tempmax.value-5
636
637         def getCurrentValue(self):
638                 return str(self["config"].getCurrent()[1].getText())
639
640         def updateFanStatus(self):
641                 global ZielRPM
642                 global AktTemp
643                 global AktVLT
644                 global AktPWM
645                 global AktRPM
646                 if config.plugins.FanControl.Fan.value == "disabled":
647                         AktTemp = 0
648                         AktVLT = 0
649                         AktPWM = 0
650                         ZielRPM = 0
651                         AktRPM = 0
652                 self["TxtTemp"].setText(_("Temperature C  %4.1f") % (AktTemp))
653                 self["TxtZielRPM"].setText(_("Target rpm  %4d") % (ZielRPM))
654                 self["TxtRPM"].setText(_("Current rpm  %4d") % (AktRPM))
655                 self["TxtVLT"].setText(_("Voltage  %03d") % (AktVLT))
656                 self["TxtPWM"].setText(_("PWM  %03d") % (AktPWM))
657                 self["PixTemp"].value = int((AktTemp-config.plugins.FanControl.temp.value)*100/Test0(config.plugins.FanControl.tempmax.value-config.plugins.FanControl.temp.value))
658                 self["PixZielRPM"].value = int((ZielRPM-config.plugins.FanControl.minRPM.value)*100/Test0(config.plugins.FanControl.maxRPM.value-config.plugins.FanControl.minRPM.value))
659                 self["PixRPM"].value = int((AktRPM-config.plugins.FanControl.minRPM.value)*100/Test0(config.plugins.FanControl.maxRPM.value-config.plugins.FanControl.minRPM.value))
660                 self["PixVLT"].value = int(AktVLT/2.55)
661                 self["PixPWM"].value = int(AktPWM/2.55)
662                 self.fan_timer.start(2000, True)
663        
664         def save(self):
665                 for x in self["config"].list:
666                         x[1].save()
667                 self.close(True,self.session)
668
669         def cancel(self):
670                 for x in self["config"].list:
671                         x[1].cancel()
672                 self.close(False,self.session)
673
674         def pruefen(self):
675                 self.session.open(FanControl2Test)
676
677         def monitor(self):
678                 self.session.open(FanControl2Monitor)
679
680         def help(self):
681                 self.session.open(Console,_("Information"),["cat /usr/lib/enigma2/python/Plugins/Extensions/FanControl2/%s" % _("readme.txt")])
682
683         def SetupMenu(self):
684                 self.session.open(FanControl2SpezialSetup)
685
686 def DeleteData():
687         if config.plugins.FanControl.DeleteData.value == "0" or config.plugins.FanControl.EnableDataLog.value == False:
688                 return
689         try:
690                 FClog("Auto-Delete Data")
691                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","a")
692                 s = f.tell()
693                 f.close()
694                 if s < 150:
695                         return
696                 f = open(config.plugins.FanControl.LogPath.value + "FC2data.csv","r")
697                 f.seek(s-100)
698                 line = f.readline()
699                 line = f.readline()
700                 DT = line.split(";")
701                 DT = DT[0].split(" ")
702                 DD = DT[0].split(".")
703                 DD48h = datetime.date(int(DD[0]),int(DD[1]),int(DD[2])) - datetime.timedelta(int(config.plugins.FanControl.DeleteData.value))
704                 Dfind = "%04d.%02d.%02d %s" % (DD48h.year,DD48h.month,DD48h.day,DT[1])
705                 f.seek(0)
706                 line = f.readline()
707                 fw = open(config.plugins.FanControl.LogPath.value + "FC2data.csv.tmp","w")
708                 fw.write(HeadLine)
709                 for line in f.readlines():
710                         DT = line.split(";")
711                         if DT[0] > Dfind:
712                                 fw.write(line)
713                 f.close()
714                 fw.close()
715                 if os.path.exists(config.plugins.FanControl.LogPath.value + "FC2data.csv"):
716                         os.remove(config.plugins.FanControl.LogPath.value + "FC2data.csv")
717                 os.rename(config.plugins.FanControl.LogPath.value + "FC2data.csv.tmp",config.plugins.FanControl.LogPath.value + "FC2data.csv")
718         except Exception:
719                 FClog("Error Delete Data")
720
721 def getstatusoutput(cmd):
722         try:
723                 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
724                 text = pipe.read()
725                 sts = pipe.close()
726                 if sts is None: sts = 0
727                 if text[-1:] == '\n': text = text[:-1]
728         except:
729                 sts = 1
730                 text = ""
731                 FClog("Error on call OS program (smartctl/hdparm)")
732         finally:
733                 return sts, text
734
735 def HDDtestTemp():
736         global disableHDDread
737         if harddiskmanager.HDDCount() > 0 and config.plugins.FanControl.CheckHDDTemp.value !="never":
738                 disableHDDread = False
739                 for hdd in harddiskmanager.HDDList():
740                         if hdd[1].model().startswith("ATA"):
741                                 FClog("%s %s Mode:%s" % (hdd[1].model(), hdd[1].getDeviceName(), config.plugins.FanControl.CheckHDDTemp.value))
742                                 if config.plugins.FanControl.CheckHDDTemp.value == "auto":
743                                         (stat,wert)=getstatusoutput("hdparm -y %s" % hdd[1].getDeviceName())
744                                         time.sleep(0.5)
745                                         (stat,wert)=ReadHDDtemp(hdd[1].getDeviceName())
746                                         if stat != 0:
747                                                 (stat,wert)=getstatusoutput("smartctl --smart=on %s" % hdd[1].getDeviceName())
748                                                 FClog("HDD Temperature not readable")
749                                         time.sleep(0.5)
750                                         (stat,wert)=getstatusoutput("hdparm -C %s" % hdd[1].getDeviceName())
751                                         if wert.find("standby")>0:
752                                                 FClog("HDD supports Temp reading without Spinup")
753                                         else:
754                                                 if hdd[1].isSleeping():
755                                                         (stat,wert)=getstatusoutput("hdparm -y %s" % hdd[1].getDeviceName())
756                                                 FClog("HDD not supports Temp reading without Spinup -> Disabled")
757                                                 disableHDDread = True
758
759 def ReadHDDtemp(D):
760         return getstatusoutput("smartctl -A %s | grep \"194 Temp\" | grep Always" % D)
761
762 def GetHDDtemp(OneTime):
763         global AktHDD
764         AktHDD = []
765         if harddiskmanager.HDDCount() > 0 and config.plugins.FanControl.CheckHDDTemp.value != "never" or OneTime == True:
766                 for hdd in harddiskmanager.HDDList():
767                         if hdd[1].model().startswith("ATA"):
768                                 sleeptime = int((time.time() - hdd[1].last_access))
769 #                               FClog("HDD Temp reading %s %s %ds %s" % (config.plugins.FanControl.CheckHDDTemp.value, disableHDDread, sleeptime, hdd[1].isSleeping()))
770                                 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:
771                                         (stat,wert)=ReadHDDtemp(hdd[1].getDeviceName())
772                                         if stat == 0:
773                                                 try:
774                                                         AktHDD.append(int(wert[wert.find("Always")+6:].replace(" ","").replace("-","")[:2]))
775                                                 except:
776                                                         AktHDD.append(0)
777                                         if len(AktHDD) == 0:
778                                                 AktHDD = [0]
779                                         FClog("HDD Temp %dC" % (AktHDD[-1]))
780         if len(AktHDD) == 0:
781                 AktHDD = [0]
782         return
783
784 def HDDsSleeping(): 
785         for hdd in harddiskmanager.HDDList():
786                 if hdd[1].model().startswith("ATA"):
787                         if not hdd[1].isSleeping():
788                                 return False
789         return True
790
791 def FC2systemStatus():
792         S = int(FC2werte[5])
793         R = " -" if S>0 else " "
794         if (S & 1)>0 :
795                 R += " BoxOn"
796         if (S & 2)>0 :
797                 R += " HDDon"
798         if (S & 4)>0 :
799                 R += " REC"
800         return R
801
802 class FanControl2(Screen):
803         skin = """ <screen position="100,100" size="300,300" title="FanControl2" > </screen>"""
804
805         def __init__(self,session):
806                 global Box
807                 Screen.__init__(self,session)
808                 self.session = session
809                 self.FanMin     = 500
810                 self.FanMax     = 1500
811                 self.targetTemp = 50.0
812                 self.maxTemp    = 55.0
813                 self.Range      = 5
814                 self.Fan        = "aus"
815                 self.dontshutdown = False
816                 FClog("Starting up")
817                 if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data/diagram.class.org"):
818                         os.rename("/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data/diagram.class.org","/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data/diagram.class")
819                 if not isDMMdisabled() and config.plugins.FanControl.DisableDMM.value:
820                         disableDMM()
821                 Box = GetBox()
822                 HDDtestTemp()
823                 GetHDDtemp(False)
824                 DeleteData()
825                 self.timer = eTimer()
826                 if self.query not in self.timer.callback:
827                         self.timer.callback.append(self.query)
828                 self.timer.startLongTimer(10)
829                 config.misc.standbyCounter.addNotifier(self.standbyQuery, initial_call = False)
830
831         def FC2AskShutdown(self):
832                 if not self.dontshutdown:
833                         self.dontshutdown = True
834                         self.session.openWithCallback(self.FC2DoShutdown, MessageBox, _("FanControl2 emergency, Box Shutdown now?"),type = MessageBox.TYPE_YESNO,timeout = 60)
835
836         def FC2DoShutdown(self,retval):
837                 if (retval):
838                         if Standby.inTryQuitMainloop == False:
839                                 self.session.open(Standby.TryQuitMainloop, 1)
840
841         def stop(self):
842                 FClog("Stop")
843                 if self.query in self.timer.callback:
844                         self.timer.callback.remove(self.query)
845                 self.timer.stop()
846
847         def CurrTemp(self):
848                 m1 = 0.1
849                 m2 = 0.1
850                 ti = [0,0,0,0,0,0,0,0,0,0]
851                 templist = sensors.getSensorsList(sensors.TYPE_TEMPERATURE)
852                 tempcount = len(templist)
853                 for count in range(tempcount):
854                         tt = sensors.getSensorValue(count)
855                         ti[count] = tt
856                         if m1 < tt:
857                                 mi = count
858                                 m1 = tt
859                 for count in range(tempcount):
860                         if m2 < ti[count] and count != mi:
861                                 m2 = ti[count]
862                 if m2 == 0.1:
863                         m2 = m1
864                 return (m1 + m2) / 2.0
865                 
866         def cycle(self):
867                 self.Range = self.maxTemp - self.targetTemp
868                 x = AktTemp - self.targetTemp
869                 rpm = skal(x, 0, self.Range, self.FanMin, self.FanMax)
870                 return rpm
871
872         def standbyQuery(self, configElement):
873                 Standby.inStandby.onClose.append(self.query)
874                 self.query()
875                 
876         def query(self):
877                 global FirstStart
878                 global istStandbySave
879                 global Overheat
880                 global OverheatTimer
881                 global FanOffWait
882                 global RPMread
883                 global RPMdiff
884                 global FanFehler            
885                 global ZielRPM
886                 global AktRPM
887                 global AktTemp
888                 global AktVLT
889                 global AktPWM
890                 global Recording
891 #               tt = time.time()
892                 try:
893                         if config.plugins.FanControl.Fan.value == "disabled":
894                                 self.timer.startLongTimer(10)
895                                 return
896                         self.targetTemp = config.plugins.FanControl.temp.value
897                         self.maxTemp    = config.plugins.FanControl.tempmax.value
898                         self.Fan        = config.plugins.FanControl.Fan.value
899                         self.Vlt        = config.plugins.FanControl.vlt.value
900                         self.HDDidle    = True
901                         id = 0
902                         AktRPMtmp = 0
903                         sleeptime = 0
904                         AktTemp = self.CurrTemp()
905                         Recording = self.session.nav.RecordTimer.isRecording()
906                         if AktTemp >= config.plugins.FanControl.ShutdownTemp.value:
907                                 FClog("Emergency Shutdown")
908                                 self.FC2AskShutdown()
909                         if harddiskmanager.HDDCount() > 0:
910                                 self.HDDidle = HDDsSleeping()
911                                 if int(strftime("%S")) < 10 and strftime("%M")[-1:] == "0":
912                                         GetHDDtemp(False)
913                                         if strftime("%H:%M") == "00:00":
914                                                 DeleteData()
915                         S=0
916                         if not Standby.inStandby:
917                                 S+=1
918                         if not self.HDDidle:
919                                 S+=2
920                         if Recording:
921                                 S+=4
922                         FC2werte[5]=str(S)
923
924                         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))):
925                                 FClog("Fan Off Temp: %d %s" % (AktTemp,FC2systemStatus()))
926                                 setVoltage(id,0)
927                                 setPWM(id,0)
928                                 FC2werte[0] = AktTemp
929                                 FC2werte[1] = 0
930                                 FC2werte[2] = 0
931                                 FC2werte[3] = 0
932 #                               FC2werte[4] = str(AktHDD)[1:-1].replace(",","")
933                                 FC2werte[4] = max(AktHDD) if len(AktHDD) > 0 else 0
934                                 FCdata()
935                                 FirstStart = True
936                                 OverheatTemp = self.maxTemp + config.plugins.FanControl.AddOverheat.value
937                                 OverheatTimer = 0
938                                 FanOffWait = True
939                                 if OverheatTemp > 65:
940                                         OverheatTemp = 65
941                                 if AktTemp > OverheatTemp:
942                                         Overheat = True
943                                         FClog("Overheat")
944                         else:
945                                 if (Overheat and AktTemp < self.maxTemp-3) or not Standby.inStandby:
946                                         Overheat = False
947                                 AktVLTtmp = getVoltage(id)
948                                 if Standby.inStandby and Standby.inStandby == istStandbySave and RPMdiff == 1 and not Recording:
949                                         tmp = GetFanRPM()
950                                         RPMdiff = AktRPM-tmp
951                                         if RPMdiff < 150 or tmp < 300 or self.Fan == "3pin":
952                                                 RPMdiff = 0
953                                         else:
954                                                 if config.plugins.FanControl.minRPM.value - RPMdiff < 300:
955                                                         RPMdiff = config.plugins.FanControl.minRPM.value - 300
956                                                 FClog("RPM-Range shifted -%drpm" % RPMdiff)
957                                 if not Standby.inStandby:
958                                         RPMdiff = 0
959                                 self.FanMin = config.plugins.FanControl.minRPM.value - RPMdiff
960                                 self.FanMax = config.plugins.FanControl.maxRPM.value - RPMdiff
961                                 if Standby.inStandby != istStandbySave or AktVLT != AktVLTtmp:
962                                         istStandbySave = Standby.inStandby
963                                         AktVLTtmp = AktVLT
964                                         setVoltage(id,AktVLT)
965                                         setPWM(id,AktPWM)
966                                         RPMdiff = 1
967                                         FClog("Fan Reset")
968                                 if (AktVLT + AktPWM) == 0:
969                                         FirstStart = True
970                                 if FirstStart == True:
971                                         FirstStart = False
972                                         AktVLTtmp = self.Vlt
973                                         setVoltage(id,self.Vlt)
974                                         setPWM(id,config.plugins.FanControl.pwm.value)
975                                 AktRPMtmp = GetFanRPM()
976                                 if RPMread>0 and RPMread<3:
977                                         FClog("Reread")
978                                         self.timer.start(400, True)
979                                         return
980                                 RPMread = 0
981                                 if AktRPMtmp > 6000:
982                                         FClog("ignore high RPM")
983                                         return
984                                 AktRPM = AktRPMtmp
985                                 AktVLT = AktVLTtmp
986                                 AktPWM = getPWM(id)
987                                 if AktVLT > 255:
988                                         AktVLT = 255
989                                 FClog("Vlt:%d Pwm:%d Fan:%s  %s" % (AktVLT,AktPWM,self.Fan,FC2systemStatus()))
990                                 FC2werte[0] = AktTemp
991                                 FC2werte[1] = AktRPM
992                                 FC2werte[2] = AktVLT
993                                 FC2werte[3] = AktPWM
994                                 FC2werte[4] = max(AktHDD) if len(AktHDD) > 0 else 0
995                                 FCdata()
996                                 if int(strftime("%M")) == 0:
997                                         FC2stunde[int(strftime("%H"))] = "%4.1f<BR>%d" % (AktTemp,AktRPM)
998                                 ZielRPM = self.cycle()
999                                 if (FanOffWait and OverheatTimer < 30) or (Overheat and OverheatTimer < 60):
1000                                         ZielRPM = self.FanMin
1001                                         OverheatTimer += 1
1002                                         FClog("FanStartTimeout set MinRPM (%d)" % (OverheatTimer)) 
1003                                 else:
1004                                         FanOffWait = False
1005                                 FClog(_("currentRPM:%d targetRPM:%d Temp:%4.1f") % (AktRPM,ZielRPM,AktTemp))
1006                                 if ZielRPM > 0 and AktRPM == 0:
1007                                         FanFehler += 1
1008                                         if FanFehler > 90:
1009                                                 FanFehler -= 18
1010                                                 FClog("Fan Error")
1011                                                 if config.plugins.FanControl.ShowError.value == "true" and not Standby.inStandby:
1012                                                         Notifications.AddNotification(MessageBox, _("Fan is not working!"), type=MessageBox.TYPE_INFO, timeout=5)
1013                                                 if config.plugins.FanControl.ShowError.value == "shutdown":
1014                                                         self.FC2AskShutdown()
1015                                 else:
1016                                         FanFehler = 0
1017                                 if self.Fan == "4pin":
1018                                         if AktPWM < 255 and AktPWM > 0 and AktVLT != self.Vlt:
1019                                                 AktVLT = (AktVLT-1 if AktVLT > self.Vlt else AktVLT+1)
1020                                                 setVoltage(id,AktVLT)
1021                                         if AktRPM+29 < ZielRPM:
1022                                                 AktPWM = (AktPWM+5 if ZielRPM-AktRPM > 100 else AktPWM+1)
1023                                                 setPWM(id,AktPWM)
1024                                                 if AktPWM >= 255 and AktVLT < 255:
1025                                                         AktVLT += 1
1026                                                         setVoltage(id,AktVLT)
1027                                         elif AktRPM-19 > ZielRPM:
1028                                                 AktPWM = (AktPWM-5 if AktRPM-ZielRPM > 100 else AktPWM-1)
1029                                                 setPWM(id,AktPWM)
1030 # 4
1031                                                 if AktPWM < 0 and AktVLT > 5:
1032                                                         AktVLT -= 1
1033                                                         setVoltage(id,AktVLT)
1034                                         if AktVLT > self.Vlt:
1035                                                 AktPWM = 256
1036                                         if AktPWM < 0:
1037                                                 AktPWM = 0
1038                                 elif self.Fan == "3pin":
1039                                         if AktRPM+29 < ZielRPM:
1040                                                 AktVLT = (AktVLT+5 if ZielRPM-AktRPM > 100 else AktVLT+1)
1041                                                 setVoltage(id,AktVLT)
1042                                         elif AktRPM-19 > ZielRPM:
1043                                                 AktVLT = (AktVLT-5 if AktRPM-ZielRPM > 100 else AktVLT-1)
1044                                                 setVoltage(id,AktVLT)
1045
1046                 except Exception:
1047                         FClog("Control Error")
1048                         import traceback, sys
1049                         traceback.print_exc(file=sys.stdout)
1050 #               FClog(str(time.time() - tt ))
1051                 self.timer.startLongTimer(10)
1052
1053 def autostart(reason, **kwargs):
1054         global session
1055         if reason == 0 and kwargs.has_key("session"):
1056                 if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/WebInterface/webif.py"):
1057                         from Plugins.Extensions.WebInterface.WebChilds.Toplevel import addExternalChild
1058                         from FC2webSite import FC2web, FC2webLog, FC2webChart
1059                         from twisted.web import static
1060                         root = static.File("/usr/lib/enigma2/python/Plugins/Extensions/FanControl2/data")
1061 #                       root = FC2web()
1062                         root.putChild("", FC2web())
1063                         root.putChild("log", FC2webLog())
1064                         root.putChild("chart", FC2webChart())
1065                         if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/WebInterface/web/external.xml"):
1066                                 addExternalChild( ("fancontrol", root, "Fan Control 2", Version) )
1067                         else:
1068                                 addExternalChild( ("fancontrol", root) )
1069                 if not os.path.exists("/proc/stb/fp/fan_vlt"):
1070                         Notifications.AddNotification(MessageBox, _("Box has no fancontrol hardware -> FC2 deactivated"), type=MessageBox.TYPE_INFO, timeout=10)
1071                         FClog("not supported, exit")
1072                         return
1073                 session = kwargs["session"]
1074                 session.open(FanControl2)
1075           
1076 def Plugins(**kwargs):
1077         list = [
1078         PluginDescriptor(name="Fan Control", 
1079         description="Fan Control 2", 
1080         where = [PluginDescriptor.WHERE_SESSIONSTART, 
1081         PluginDescriptor.WHERE_AUTOSTART], 
1082         fnc = autostart)]
1083         if os.path.exists("/proc/stb/fp/fan_vlt"):
1084                 list.append(PluginDescriptor(name="Fan Control 2", 
1085                 description="Fan Control", 
1086                 where = PluginDescriptor.WHERE_PLUGINMENU,
1087                 icon = "plugin.png",
1088                 fnc = main))
1089                 if config.plugins.FanControl.FanControlInExtension.value:
1090                         list.append(PluginDescriptor(name="Fan Control 2", 
1091                         description="Fan Control", 
1092                         where = PluginDescriptor.WHERE_EXTENSIONSMENU,
1093                         icon = "plugin.png",
1094                         fnc = main))
1095                 if config.plugins.FanControl.MonitorInExtension.value:
1096                         list.append(PluginDescriptor(
1097                         name="Fan Control 2 - Monitor", 
1098                         description="Fan Control", 
1099                         where = PluginDescriptor.WHERE_EXTENSIONSMENU,
1100                         icon = "plugin.png",
1101                         fnc = mainMonitor))
1102         return list