原来一直用C写的温控,但是想实现的很多功能都做不到——主要是C学得一点毛皮就开始写——但是习惯了Java想要什么功能就有什么包,以及成熟的IDE(好吧就是我智障总是写bug),所以决定改写成Java版本的。但是之前一直习惯了C和Linux的紧密相连,思路也是shell的思路,所以在Java里面也下意识想要用Process类的exec()来执行echo命令——风扇控制、频率限制都是通过写入文件来实现的。实际上因为exec()并不是一个shell,所以这样做是不行的。要想写入文件,还是要通过正式的FileWriter等类来实现。
现在剩下的问题是怎么在IDE里实现用root权限测试程序,不然每次都要去terminal里sudo真是很烦恼。
参考了: Java FileWriter类 Java FileReader类 CSDN - Java将字符串写入文件与将文件内容读取到字符串 Techie Delight - Convert char array to String in Java CSDN - intellij idea 导出可执行jar
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
| import java.io.*;
import static java.lang.Thread.sleep;
public class Thermal { private static int[] tempSteps = {48, 50, 55, 60, 70, 80, 84, 90}; private static Boolean freqLimitOn = false;
private static int temperatureReader() throws IOException { char[] temp = new char[2]; FileReader reader0 = new FileReader(new File("/sys/class/thermal/thermal_zone0/temp")); FileReader reader1 = new FileReader(new File("/sys/class/thermal/thermal_zone1/temp"));
reader0.read(temp); int temp0 = Integer.parseInt(String.valueOf(temp)); reader1.read(temp); int temp1 = Integer.parseInt(String.valueOf(temp));
return ((temp0 >= temp1) ? temp0 : temp1);
}
private void fancontroller(int level) throws IOException { FileWriter fw = new FileWriter("/proc/acpi/ibm/fan", false); fw.write("level " + level); fw.flush(); }
private void levelJudge(int temperature) throws IOException { for (int i = tempSteps.length - 1; i >= 0; i--) { if (temperature >= tempSteps[i]) { fancontroller(i); break; }
} }
private static void freqLimitSetter(long freq) throws IOException { FileWriter fw; String filepath; for (int i = 0; i <= 7; i++) { filepath = String.format("/sys/devices/system/cpu/cpufreq/policy%d/scaling_max_freq", i); fw = new FileWriter(filepath, false); fw.write("" + freq); fw.flush(); fw.close(); } }
private void freqthrottle() throws IOException {
if ((temperatureReader() > 84) && !freqLimitOn) { freqLimitSetter(2100000); freqLimitOn = true; System.out.println("limited cpu freq"); } else if (freqLimitOn) { freqLimitSetter(3500000); System.out.println("unlimited cpu freq"); }
}
public static void main(String[] args) { Thermal thermal = new Thermal(); try { while (true) { thermal.levelJudge(temperatureReader()); thermal.freqthrottle(); sleep(5000); }
} catch (InterruptedException | IOException e) { e.printStackTrace(); }
}
}
|