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
| import os import requests import json import time
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])
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])
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)
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)
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())
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()
|