Files
PyFan/pyfan.py

173 lines
6.5 KiB
Python

#!/usr/bin/env python
import glob
import logging
import re
import sys
from time import sleep
import yaml
from simple_pid import PID
SYSFS_HWMON_BASE = "/sys/class/hwmon/"
class ThermalZone:
def __init__(self, config, hwmon_map) -> None:
self.fans = config["fan"]
self.temp_source = config["source"]
self.pid = PID(config["pid"]["p"], config["pid"]["i"], config["pid"]["d"], setpoint=0)
self.pid.output_limits = (0, 255)
self.factor = 1 / config["factor"]
self.name = config["name"]
self.target = config["target"]
self.hwmap = hwmon_map
self.alias_replace = re.compile('|'.join(self.hwmap.keys()))
self.setup_pwm()
logging.getLogger("pyfan").info(
"[{zone}] Source={source} Fans={fans} Factor={factor} PID={pid}".format(zone=self.name,
source=self.temp_source,
fans=self.fans,
factor=self.factor,
pid=(
self.pid.Kp, self.pid.Ki,
self.pid.Kd)))
def eval(self):
if self.get_temp():
diff = self.target - self.get_temp()
val = int(self.pid(diff))
try:
for target_fan in self.fans:
if type(target_fan) is dict:
fan = list(target_fan.keys())[0]
fan_val = list(target_fan.values())[0]
if type(fan_val) is list:
if len(fan_val) < 2:
logging.getLogger("pyfan").warning(
"[%s] max/min for %s was not set correctly (%s)" % (self.name, fan, fan_val))
self.write_sysfs(fan, min(fan_val[1], max(val, fan_val[0])))
else:
self.write_sysfs(fan, min(val, fan_val))
logging.getLogger("pyfan").debug(
"[{name}] {fan} is set at {val}%".format(name=self.name, fan=fan,
val=int(int(self.read_sysfs(fan)) / 255 * 100)))
else:
self.write_sysfs(target_fan, val)
except OSError as err:
logging.getLogger("pyfan").warning(
"[%s] Failed to set pwm, trying to reset it. (%s)" % (self.name, err.strerror))
self.setup_pwm(1)
p, i, d = self.pid.components
logging.getLogger("pyfan").debug(
"[{name}] {val}% ({diff}C/{temp}C) ({p}|{i}|{d})".format(name=self.name, val=int(val / 255 * 100),
diff=diff,
temp=self.get_temp(), p=int(p), i=int(i),
d=int(d)))
def get_temp(self):
if self.read_sysfs(self.temp_source):
return float(self.read_sysfs(self.temp_source)) * self.factor
else:
return None
def restore(self):
self.setup_pwm(2)
def setup_pwm(self, value=1):
for target_fan in self.fans:
try:
if type(target_fan) is dict:
self.set_pwm_mode(list(target_fan.keys())[0], value)
else:
self.set_pwm_mode(target_fan, value)
except FileNotFoundError as err:
logging.getLogger("pyfan").warning("[%s] pwm not found."
" Not ready yet or wrong path? (%s)" % (self.name, err.strerror))
def replace_alias(self, path):
replaced = self.alias_replace.sub(lambda x: self.hwmap[x.group()], path)
logging.getLogger("pyfan").debug("[ALIAS] %s -> %s" % (path, replaced))
return replaced
def build_pwm_path(self, specific):
return self.replace_alias(SYSFS_HWMON_BASE + specific)
def write_sysfs(self, path, value):
with open(self.build_pwm_path(path), 'w') as sysfs_f:
sysfs_f.write(str(value))
def read_sysfs(self, path):
try:
with open(self.build_pwm_path(path)) as sysfs_f:
return sysfs_f.readline()
except FileNotFoundError as err:
logging.getLogger("pyfan").warning(
"[%s] temp source not found. Not ready yet or wrong path? (%s)" % (self.name,
err.strerror))
return None
def set_pwm_mode(self, path, value=1):
self.write_sysfs(path + "_enable", value)
class PyFan:
def __init__(self, config="/etc/pyfan") -> None:
self.config = self.__load_config(config)
logging.basicConfig(level=logging.getLevelName(self.config["loglevel"]))
self.zones = []
self.hwmon_map = {}
self.gen_hwmon_map()
if "interval" in self.config:
self.interval = self.config["interval"]
else:
self.interval = 1
for zone in self.config["thermalzones"]:
self.zones.append(ThermalZone(zone, self.hwmon_map))
logging.getLogger("pyfan").info(
"Finished creating %d thermal zones, checking all %d seconds" % (len(self.zones), self.interval))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
for zone in self.zones:
zone.restore()
def eval(self):
for zone in self.zones:
zone.eval()
@staticmethod
def __load_config(path):
with open(path) as cfg_file:
return yaml.safe_load(cfg_file)
def gen_hwmon_map(self):
names = glob.glob(SYSFS_HWMON_BASE + "hwmon*/name")
for name in names:
hwmon = name.split("/")[-2]
with open(name) as file:
hwname = file.read().strip()
self.hwmon_map[hwname] = hwmon
if __name__ == "__main__":
with PyFan() as pyfan:
while True:
try:
pyfan.eval()
sleep(pyfan.interval)
except KeyboardInterrupt:
sys.exit(0)