1. 程式人生 > >打造自己的樹莓派監控系統1--CPU監控

打造自己的樹莓派監控系統1--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

然後在瀏覽器中開啟http://127.0.0.1:4000/cpu即可看到樹莓派CPU溫度-時間圖:
在這裡插入圖片描述