-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfan-control
executable file
·83 lines (71 loc) · 1.89 KB
/
fan-control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
""" Fan Control for raspberry pi 5 - tested on Raspberry Pi 5 Model B, kernel 6.8.0 """
from enum import Enum
import time
import os
import sys
class FanSpeed(Enum):
""" Symbolics for fan speed input """
OFF = 0
LOW = 1
MEDIUM = 2
HIGH = 3
FULL = 4
class Fan:
def __init__(self):
self.fan_path = "/sys/class/thermal/cooling_device0/cur_state"
self.temp_path = "/sys/devices/virtual/thermal/thermal_zone0/temp"
self.ranges = {
70: FanSpeed.FULL,
65: FanSpeed.HIGH,
60: FanSpeed.MEDIUM,
55: FanSpeed.LOW,
54: FanSpeed.OFF
}
@property
def speed(self) -> FanSpeed:
with open(self.fan_path) as f:
speed = int(f.read().strip())
return FanSpeed(speed)
def set_speed(self, speed: FanSpeed):
with open(self.fan_path, "w") as f:
f.write(str(speed.value))
return self
def get_temp(self) -> float:
with open(self.temp_path, "r") as f:
data = f.read().strip()
return float(data) / 1000
def adjust_for_temp(self):
temp = self.get_temp()
cspeed = self.speed
speed = cspeed
for level, spd in self.ranges.items():
if temp >= level:
speed = spd
#print(temp,level,spd)
break
self.set_speed(speed)
def main():
check_paths = [ "/sys/class/thermal/cooling_device0/cur_state",
"/sys/devices/virtual/thermal/thermal_zone0/temp"]
fail = False
for p in check_paths:
if not os.path.exists(p):
print(f"Cannot find control interface at {p}",file=sys.stderr)
fail = True
if fail:
print('Required control interfaces are not present. Please ensure any required kernel modules are loaded.',file=sys.stderr)
sys,exit(-1)
fan = Fan()
if os.getuid() != 0:
print("fan control must be run as root",file=sys.stderr)
sys.exit(-13)
print("Fan control started")
while True:
try:
fan.adjust_for_temp()
except Exception as e:
print(f'adjust-for-temp: {e}',file=sys.stderr)
time.sleep(2)
if __name__ == "__main__":
main()