打造自己的樹莓派監控系統2--記憶體監控
阿新 • • 發佈:2018-11-28
程式碼編寫
樹莓派的記憶體使用情況可以使用如下命令檢視:
free -m
結果如下:
total used free shared buff/cache available
Mem: 927 353 32 48 540 470
Swap: 0 0 0
而’free -m’命令是通過檢視/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地址: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/mem即可看到樹莓派記憶體使用情況-時間圖: