#!/bin/bash
# https://www.kernel.org/doc/html/latest/hwmon/it87.html
# https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=2cbb9c370fe32b5de5243f7338dc6ce8747d495b
set -eux
modprobe it87
CT="$(grep -l coretemp /sys/class/hwmon/hwmon*/name | head -n1 | xargs dirname)/temp1_input"
cd "$(grep -l it8792 /sys/class/hwmon/hwmon*/name | head -n1 | xargs dirname)"
grep . pwm1* temp1*
# automatic fan control - the chip seems to ignore these settings
#echo 2 > pwm1_enable # automatic mode
#echo 1 > pwm1_auto_channels_temp # temperature channel
#echo 127000 > pwm1_auto_point1_temp_hyst # ??
#echo 127000 > pwm1_auto_point1_temp # fan off temp
#echo 127000 > pwm1_auto_point2_temp # fan start temp
#echo 127000 > pwm1_auto_point3_temp # fan max temperature
#echo 100 > pwm1_auto_start # start pwm value
#echo 0 > pwm1_auto_slope # pwm slope, 1/8th pwm
# manual fan control - magic incantation
echo 1 > pwm1_enable # manual mode
echo 200000 > pwm1_freq # quieter fan
echo 0 > temp3_type # disabled unused sensor
echo 4 > temp1_type # switch sensor to thermistor
sleep 1 # wait for driver to write to chip
echo 0 > temp1_type # disable the sensor
echo 42 > pwm1 # set the fan speed
grep . *pwm1* temp1*
set +x
OLDPWM="$(cat pwm1)"
while sleep 1; do
TEMPC="$(cat "$CT")"
if [ "$TEMPC" -ge 85000 ]; then
NEWPWM=255
elif [ "$TEMPC" -ge 80000 ]; then
NEWPWM=180
elif [ "$TEMPC" -ge 60000 ]; then
NEWPWM=130
else
NEWPWM=100
fi
if [ "$OLDPWM" -ne "$NEWPWM" ]; then
echo "Fan speed change: OLDPWM=$OLDPWM TEMPC=$TEMPC NEWPWM=$NEWPWM"
echo "$NEWPWM" > pwm1
OLDPWM="$NEWPWM"
sleep 30
fi
done