generated from egvimo/template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
84 lines (64 loc) · 2.26 KB
/
main.py
File metadata and controls
84 lines (64 loc) · 2.26 KB
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
84
import logging
import os
import time
from gpiozero import CPUTemperature, PWMOutputDevice
from gpiozero.pins.rpigpio import RPiGPIOFactory
from schedule import every, repeat, run_pending
# Constants
TEMPERATURE_TARGET = float(os.getenv("TEMPERATURE_TARGET", 45.0))
TEMPERATURE_TOLERANCE = 3.0
SPEED_ADJUSTMENT = 5.0
INITIAL_FAN_SPEED = 50.0
# GPIO setup
_FACTORY = RPiGPIOFactory()
_FAN = PWMOutputDevice(18, pin_factory=_FACTORY)
# Logging setup
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
def _read_temperature() -> float:
"""Read CPU temperature in Celsius."""
return CPUTemperature().temperature
def _adjust_speed(adjustment: float):
"""Adjust fan speed within valid range (0-100%)."""
current_speed = _FAN.value * 100
target_speed = min(max(current_speed + adjustment, 0), 100)
if current_speed != target_speed:
logging.info(
"Adjusting speed from %.1f%% to %.1f%%", current_speed, target_speed
)
_FAN.value = target_speed / 100
@repeat(every(30).seconds)
def check_temperature():
"""Check CPU temperature and adjust fan speed accordingly."""
temperature = _read_temperature()
if temperature > TEMPERATURE_TARGET + TEMPERATURE_TOLERANCE:
logging.info("Temperature high (%.1f°C), increasing fan speed", temperature)
_adjust_speed(SPEED_ADJUSTMENT)
elif temperature < TEMPERATURE_TARGET - TEMPERATURE_TOLERANCE:
logging.info("Temperature low (%.1f°C), decreasing fan speed", temperature)
_adjust_speed(-SPEED_ADJUSTMENT)
@repeat(every(10).minutes)
def log_current_state():
"""Log current CPU temperature and fan speed."""
current_speed = _FAN.value * 100
temperature = _read_temperature()
logging.info(
"Current temperature: %.1f°C, Fan speed: %.1f%%", temperature, current_speed
)
def start():
"""Start the fan controller with an initial speed."""
logging.info(
"Starting fan controller with initial speed of %.1f%%", INITIAL_FAN_SPEED
)
try:
_FAN.on()
_FAN.value = INITIAL_FAN_SPEED / 100
while True:
run_pending()
time.sleep(5)
except Exception:
_FAN.off()
raise
if __name__ == "__main__":
start()