文章1:打造自己的树莓派监控系统1–CPU监控-matplotlib显示数据
文章2:打造自己的树莓派监控系统2–内存监控-matplotlib显示数据
文章3:打造自己的树莓派监控系统3–canvas.js绘制数据
GitHub仓库:树莓派系统监控–CPU温度监控和内存使用监控
树莓派的CPU温度是存放在一个文件里,使用如下命令查看CPU温度:
cat /sys/class/thermal/thermal_zone0/temp
输出的是五位的整数,除以1000就是CPU的温度了。
python代码如下:
def get_temperature():
try:
cpu_temp_file = open("/sys/class/thermal/thermal_zone0/temp")
cpu_temp = cpu_temp_file.read()
return cpu_temp
except Exception as e:
print(e)
finally:
cpu_temp_file.close()
然后我使用Python自带的sqlite数据库存储数据:
def create():
global conn
conn = sqlite3.connect('data.db')
conn.execute("""
create table if not exists temperature(
id INTEGER PRIMARY KEY ,
temperature INTEGER DEFAULT NULL,
time INTEGER DEFAULT NULL)""")
conn.commit()
def save(temperature):
# 将数据保存至本地
global conn
command1 = "insert into temperature \
(temperature,time) values (?,?);"
try:
temp = (temperature, int(round(time.time() * 1000)))
conn.execute(command1, temp)
except Exception as e:
print(e)
print("insert error!")
conn.rollback()
conn.commit()
最后是画图:
def cpu():
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
global conn
temperature = cpu_get()
ID = len(temperature)
past = datetime.datetime.now()-datetime.timedelta(minutes=ID)
x = [past+datetime.timedelta(minutes=i)
for i in range(ID)]
plt.title("time and cpu temperature", fontsize=25)
plt.xlabel("time", fontsize=15)
plt.ylabel("cpu temperature", fontsize=15)
plt.plot(x, temperature)
plt.ylim(20 if 20 < min(temperature) else min(temperature),
100 if 100 > max(temperature) else max(temperature))
plt.gcf().autofmt_xdate()
plt.savefig('static/temperature.jpg')
此项目的GitHub地址:zhang0peter/raspberry-pi-monitor: 树莓派系统监控
运行如下命令:
git clone https://github.com/zhang0peter/raspberry-pi-monitor.git
cd raspberry-pi-monitor/
screen -S raspberry-pi-monitor
bash main.sh