自分のベリーパイモニタリングシステムを構築2--メモリモニタリング-matplotlib表示データ


シリーズ記事:
  • 文章1:自分のベリーパイ監視システムを作る1–CPU監視-matplotlib表示データ
  • 記事2:自分のベリーパイ監視システムを構築する2–メモリ監視-matplotlib表示データ
  • 文章3:自分のベリーパイ監視システムを作る3-canvas.jsペイントデータ
  • GitHub倉庫:樹莓派システム監視–CPU温度監視とメモリ使用監視
  • コード作成
    ベリーパイのメモリ使用状況は、次のコマンドで確認できます.
    free -m
    

    結果は次のとおりです.
                  total        used        free      shared  buff/cache   available
    Mem:            927         353          32          48         540         470
    Swap:             0           0           0
    

    一方、「free-m」コマンドは、/proc/meminfoファイルを表示/proc/meminfoファイルから情報を取得します.
    cat /proc/meminfo
    

    次のコマンドを使用して、使用可能なメモリを表示します.
    cat /proc/meminfo | grep MemAvailable
    

    次に、書き込みコードを開始します.メモリを取得します.
    def get_mem():
        try:
            MemAvailable = os.popen(
                "cat /proc/meminfo | grep MemAvailable |awk  '{print $2 / 1024}'").readline()
            MemAvailable = float(MemAvailable)
            return MemAvailable
        except Exception as e:
            print(e)
    

    データはデータベースに保存されます.
    def create():
        #      
        global conn
        conn = sqlite3.connect('data.db')
        conn.execute("""
                    create table if not exists mem(
                    id INTEGER PRIMARY KEY ,
                    mem DOUBLE DEFAULT NULL,
                    time INTEGER DEFAULT NULL)""")
        conn.commit()
    def save(mem):
        #         
        global conn
        command1 = "insert into mem \
                 (mem,time) values (?,?);"
        try:
            temp = (mem, int(round(time.time() * 1000)))
            conn.execute(command1, temp)
        except Exception as e:
            print(e)
            print("insert error!")
            conn.rollback()
        conn.commit()
    

    最後に絵を描きます.
    def mem():
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        global conn
        connect()
        mem,MemTotal = mem_get()
        ID = len(mem)
        past = datetime.datetime.now()-datetime.timedelta(minutes=ID)
        x = [past+datetime.timedelta(minutes=i)
             for i in range(ID)]
        plt.title("time and memory usage", fontsize=25)
        plt.xlabel("time", fontsize=15)
        plt.ylabel("memory usage", fontsize=15)
        plt.plot(x, mem)
        plt.ylim(0,MemTotal)
        plt.gcf().autofmt_xdate()
        plt.savefig('static/mem.jpg')
    

    うんてん
    このプロジェクトのGitHubアドレス:zhang 0 peter/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/memベリーパイのメモリ使用状況-時間図を表示します.