LoginSignup
6
6

More than 3 years have passed since last update.

[RaspberryPi] cpu温度をリアルタイム監視

Last updated at Posted at 2020-07-23

0. 目的

Raspberry Piのcpu温度を定期的に取得 & リアルタイムでグラフに表示

1. 環境

  • 端末 : Raspberry Pi 4 Model B 4[GB]
  • OS : Raspbian(buster)
  • 言語 : Python3.7.3

2. ソースコード

cpu_tempreture.py

import re
import os
import csv
import time
import datetime
import subprocess
import numpy as np
from matplotlib import pyplot as plt

# マクロ
UPDATE_TIME = 15    # 指定した分数ごとにcpu温度を取得
FIG_X = 19.2        # グラフウィンドウの横サイズ
FIG_Y = 4           # グラフウィンドウの縦サイズ
X_MIN = 0           # x軸(時刻)の最小値
X_MAX = 24          # x軸(時刻)の最大値
Y_MIN = 0           # y軸(cpu温度)の最小値
Y_MAX = 100         # y軸(cpu温度)の最大値
COLOR = "tab:green" # グラフの色
MARKER = "o"        # マーカーの形
MARKER_SIZE = 5     # マーカーの大きさ

def main():

    init = initialize()

    while(1):

        info = get_info()

        if(info[0] != info[1]): # 現在の年月日と直前に取得した年月日が異なる場合(日を跨いだ場合)
            # 年月日の更新
            with open("date.txt", "w") as f:
                f.write(info[1])
            # listの初期化
            init[0].clear()
            init[1].clear()

        add_data(info) # logの取得

        # グラフ表示
        init[0].append(int(info[3]))
        init[1].append(float(info[4]))
        display_graph(init, info)

        time.sleep(UPDATE_TIME * 60) # 引数の時間の間待機

#--logファイルの生成 & グラフの設定--#
def initialize():

    if not os.path.exists("date.txt"):
        subprocess.run( ["touch", "date.txt"] ) 
    if not os.path.exists("log"):
        subprocess.run( ["mkdir", "log"] )

    plt.figure(figsize=(FIG_X, FIG_Y))
    x, y, x_scale, x_scale_encode = [], [], [], []

    for i in range (25):
        x_scale.append(i * 60) # 0*60[m] ~ 24*60[m]
        x_scale_encode.append(str(i) + ":00") # 0:00 ~ 24:00

    return x, y, x_scale, x_scale_encode

#--現在の年月日、時刻、cpu温度を取得--#
def get_info():

    # 以前書き込みを行った年月日を取得
    with open("date.txt", "r") as f:
        date_old = f.read() 

    # 現在の年月日を取得
    date_now = str(datetime.date.today())

    # 現在の時刻の取得
    proc = subprocess.run(["date", "+%H.%M"], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    proc_time = re.split("[\n]", (proc.stdout.decode("utf8")))
    if(proc_time[0][0:1] == "0"): # 0~9時代の時
        proc_time[0] = proc_time[0][1:5] # 先頭の'0'を削除
    proc_time_encode = (int(proc_time[0].split(".")[0]) * 60) + (int(proc_time[0].split(".")[1])) # 0:00から経過した分数に変換

    # 現在のcpu温度の取得
    proc = subprocess.run(["vcgencmd", "measure_temp"], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    proc_tmp = re.split("[=\']", proc.stdout.decode("utf8"))

    return date_old, date_now, proc_time[0], str(proc_time_encode), proc_tmp[1]

#--データの追記--#
def add_data(info):

    with open("log/" + info[1] + ".csv", "a") as f:
        writer = csv.writer(f)
        if(info[0] != info[1]):
            writer.writerow( ["time", "cpu_temperature [℃]"] )
        writer.writerow( [info[2].replace(".", ":"), info[4]] )

#--グラフの表示--#
def display_graph(init, info):

    # グラフの初期化
    plt.cla()

    # 表示形式の設定
    plt.title("cpu_temperature_" + info[1]) # グラフタイトルの表示
    plt.xlim(X_MIN, X_MAX * 60) # x軸の表示範囲
    plt.ylim(Y_MIN, Y_MAX) # y軸の表示範囲
    plt.xlabel("time") # x軸のラベル
    plt.ylabel("cpu_temperature [℃]") # y軸のラベル
    plt.xticks(init[2], init[3]) # x軸の目盛りの表示形式を変更

    # 描画
    plt.plot(init[0], init[1], color=COLOR, marker=MARKER, markersize=MARKER_SIZE)
    plt.pause(0.1)

if __name__ == "__main__":
    main()

2_1. 解説

  • 関数, コマンド
    • subprocess.run : pythonでシェルコマンドを実行
    • vcgencmd measure_temp : cpu温度を表示するシェルコマンド
  • グラフ
    • x, y共に指定された時間ごとに取得したデータを配列に格納
    • 日を跨いだら配列の要素を削除することで、前日のグラフを消去
    • 横軸
      • 0:00から何分経過したかを取得(0[分]~24*60[分])
      • plt.xticks() : 第1引数の値を第2引数の値で置換する。これにより、0[分]~24*60[分]を0:00~24:00と表示

3. 実行結果

「./log/YYYY_MM_DD.csv」に下記の様式でlogが保存される
cpufanをオフにした20:26以降はcpu温度が上昇していることが確認できる

time cpu_temperature [℃]
16:41 47.0
16:56 44.0
17:11 45.0
17:26 45.0
17:41 44.0
17:56 45.0
18:11 45.0
18:26 44.0
18:41 44.0
18:56 45.0
19:11 45.0
19:26 45.0
19:41 44.0
19:56 45.0
20:11 45.0
20:26 55.0
20:41 61.0
20:56 62.0
21:11 63.0
21:26 64.0
21:41 64.0
21:56 63.0
... ...

グラフ
図1.png

4. 備考

グラフの諸設定は「# マクロ」にて変更可能

ex) logの更新頻度を10分に変更
UPDATE_TIME = 15 → UPDATE_TIME = 10

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6