树莓派的/proc/文件夹中有各种虚拟文件,可以用来读取系统的各种数据。
下面以读取内存使用率、CPU使用率、CPU温度为例进行演示,用JSP页面实现。代码中的说明部分写明了所要读取的文件和计算方法。
代码片段:
-function:get memery usage
-method:(read /proc/meminfo)
-calculation:
total memery = MemTotal
mem free = MemFree + Buffers + Cached
mem usage = MemTotal - mem free
--%>
FileReader fr_mem_usage=new FileReader("/proc/meminfo");
BufferedReader br_mem_usage=new BufferedReader(fr_mem_usage);
String s_mem_total=br_mem_usage.readLine();
String s_mem_free=br_mem_usage.readLine();
String s_mem_buffers=br_mem_usage.readLine();
String s_mem_cached=br_mem_usage.readLine();
String[] s_mem_total_array = s_mem_total.split("\\s+");
String[] s_mem_free_array = s_mem_free.split("\\s+");
String[] s_mem_buffers_array = s_mem_buffers.split("\\s+");
String[] s_mem_cached_array = s_mem_cached.split("\\s+");
int mem_total = Integer.parseInt(s_mem_total_array[1]);
int mem_free = Integer.parseInt(s_mem_free_array[1]);
int mem_buffers = Integer.parseInt(s_mem_buffers_array[1]);
int mem_cached = Integer.parseInt(s_mem_cached_array[1]);
int memUsage = 100 - (100 * (mem_free + mem_buffers + mem_cached) / mem_total);
fr_mem_usage.close();
br_mem_usage.close();
%>
-function:get cpu usage
-method:(read /proc/stat)
-calculation:
CPU total time=user+nice+system+idle+iowait+irq+softirq
cpu usage=(idle2-idle1)/(cpu2-cpu1)*100
OR cpu usage=[(user_2 +sys_2+nice_2) - (user_1 + sys_1+nice_1)]/(total_2 - total_1)*100
--%>
FileReader fr_cpu_usage1=new FileReader("/proc/stat");
BufferedReader br_cpu_usage1=new BufferedReader(fr_cpu_usage1);
String s_cpu_usage1=br_cpu_usage1.readLine();
String[] s_cpu_usage_array1 = s_cpu_usage1.split("\\s+");
int f_cpu_usage_array1[] = new int[7];
for(int i=1;i<=7;i++){
f_cpu_usage_array1[i-1] = Integer.parseInt(s_cpu_usage_array1[i]);
}
fr_cpu_usage1.close();
br_cpu_usage1.close();
Thread.sleep(100);
FileReader fr_cpu_usage2=new FileReader("/proc/stat");
BufferedReader br_cpu_usage2=new BufferedReader(fr_cpu_usage2);
String s_cpu_usage2=br_cpu_usage2.readLine();
String[] s_cpu_usage_array2 = s_cpu_usage2.split("\\s+");
int f_cpu_usage_array2[] = new int[7];
for(int i=1;i<=7;i++){
f_cpu_usage_array2[i-1] = Integer.parseInt(s_cpu_usage_array2[i]);
}
fr_cpu_usage2.close();
br_cpu_usage2.close();
int cputotal1=0,cputotal2=0,idle1=0,idle2=0,cpuUsage=0;
for(int i=0;i<=6;i++){
cputotal1 = cputotal1 + f_cpu_usage_array1[i];
}
for(int i=0;i<=6;i++){
cputotal2 = cputotal2 + f_cpu_usage_array2[i];
}
idle1 = f_cpu_usage_array1[3];
idle2 = f_cpu_usage_array2[3];
cpuUsage = 100 - (100 * (idle2 - idle1)/(cputotal2 - cputotal1));
%>
-function:get cpu temperature
-method:(read /sys/class/thermal/thermal_zone0/temp)
-calculation:
actual temperature = number_you_read / 1000
--%>
FileReader fr=new FileReader("/sys/class/thermal/thermal_zone0/temp");
BufferedReader br=new BufferedReader(fr);
String s=br.readLine();
int temp = (Integer.parseInt(s))/1000;
fr.close();
br.close();
%>
结束