#!/usr/bin/perl -w

# > ls -l /dev/fancontrol 
# lrwxrwxrwx 1 root root 7 Aug  3 12:32 /dev/fancontrol -> ttyUSB0

open("F", ">/dev/fancontrol") || die;
sleep 2;

@lasttemps = ();
$lookBack = 5;

while (1) {
  @temps = `cat /sys/devices/platform/coretemp.0/temp*_input`;
  chomp @temps;

  @temps2 = sort {$b <=> $a} @temps;
  $max = $temps2[0] / 1000;

  push @lasttemps, ($max);
  if (@lasttemps > $lookBack) { shift @lasttemps; }  # delete the first one

# foreach (@lasttemps) {
#  print "$_ ";
# }
# print "\n";

  print "temp=$max";

  foreach (@lasttemps) {
    if ($max < $_) { $max = $_; }
  }
  print "   maxTemp in last $lookBack seconds: $max";

 
  $high = 68;
  $maxhigh = 75;
  $low  = 48;

  if    ($max >= $maxhigh) {   }
  elsif ($max <  $low) { print F "P 95\n"; }   # stop fan 100%-ig
  else  {
     $h1 = $max - $low;
     $strech = $high - $low;
     $proz = 100 - int($h1 / $strech * 100);
     if ($proz > 95) { $proz = 95; }
     if ($proz < 0) { $proz = 0; }
     print "   fan stop prozent=$proz";
     print F "P $proz\n";
  }
  print "\n";

  sleep(1);
}

close F;

