Python监测树莓派温度状态

4月底气温已经慢慢升高了,之前树莓派没有增加散热片以及风扇,导致温度太高,把TF卡给烧坏了(心疼3S)。
为了不要让这种事情发生,立马把风扇给配上了。虽然把风扇加上了,为了再多加一个保险,自己用Python写了一个监控脚本,当温度达到某个值时,将会发送到微信报警。

获取系统状态

首先,我们需要知道树莓派各项参数。

CPU相关

树莓派获取CPU温度的命令是:

vcgencmd measure_temp

获取CPU使用情况可以通过top来抓取到。
因为我只需要获取到cpu的使用情况,所以通过aws可以匹配抓取到我们想要的数据

top -n1 | awk ‘/Cpu(s):/ {print $2}’

内存使用情况

通过 free命令可以得到我们当前内存的使用情况

获取磁盘状态

df -h /

通知服务

这里使用的微信提醒服务是 Server酱,Server酱是从服务器推报警和日志到手机的工具,特方便的一点就是,只有一个接口,并且直接使用github登陆即可注册。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# coding=utf-8
import os
import requests
import json
import time

# 获取CPU温度
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))

# 获取内存状态
def getRAMinfo():
p = os.popen('free')
i = 0
while 1:
i = i + 1
line = p.readline()
if i==2:
return(line.split()[1:4])

# 获取CPU使用情况
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))

# 获取磁盘状态
def getDiskSpace():
p = os.popen("df -h /")
i = 0
while 1:
i = i +1
line = p.readline()
if i==2:
return(line.split()[1:5])

# POST 到自己的服务器上 之后做他用
def getPostServer(CPUData):
url = "http://xxx.xxx/xxx"
CPUData['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
requests.post (url, data = CPUData) # 将数据POST到服务器上



# 发送数据到微信
def getPostWinxin(CPUData):
url = "https://sc.ftqq.com/you token.send"
param = {'text':'树莓派温度达到' + CPUData['CPU_temp'] + '°C了', 'desp':'## 树莓派信息 \n > CPU 温度 = ' +CPUData['CPU_temp'] + '°C \nCPU 用量 = '+ CPUData['CPU_usage'] + '% \n总内存 = '+str(CPUData['RAM_total'])+' MB \n使用内存 = '+str(CPUData['RAM_used'])+' MB \n剩余内存 = '+str(CPUData['RAM_free'])+' MB \n磁盘空间 = '+str(CPUData['DISK_total'])+'B \n已使用 = '+str(CPUData['DISK_used'])+'B \n百分比 = '+str(CPUData['DISK_perc'])}
requests.post (url, data = param)

# 检查字符串是否是JSON格式 是则返回对象
def check_json(strData):
try:
return json.loads(strData)
except:
return False

RAM_stats = getRAMinfo()
DISK_stats = getDiskSpace()
data = {
'CPU_temp' : getCPUtemperature(),
'CPU_usage': getCPUuse(),
'RAM_stats': getRAMinfo(),
'RAM_total': round(int(RAM_stats[0]) / 1000,1),
'RAM_used' : round(int(RAM_stats[1]) / 1000,1),
'RAM_free' : round(int(RAM_stats[2]) / 1000,1),
'DISK_total' : DISK_stats[0],
'DISK_used' : DISK_stats[1],
'DISK_perc' : DISK_stats[3]

}

getPostServer(data)

if float(data['CPU_temp']) > 60.0:
filePath = "/home/pi/pi.json"
if not os.path.exists(filePath):
fileData = open(filePath, 'w+')
else:
fileData = open(filePath, 'rw+')
fileStrArr = check_json(fileData.read())


# 如果文本不存在数据或者不是标准的JSON 格式
if not fileStrArr:
fileArr = {"time":int(time.time()), 'number': 1}
getPostWinxin(data)
else:
nowtime = int(time.time())
if fileStrArr['time'] + 1800 < nowtime:
fileArr = {"time":int(time.time()), 'number': fileStrArr['number'] + 1}
getPostWinxin(data)
else:
fileArr = fileStrArr
fileData.write(json.dumps(fileArr))
fileData.close()
作者

MartialBE

发布于

2018-05-03

更新于

2018-05-03

许可协议

评论