检测树莓派温度
树莓派内部有温度传感器,所以只需要调用传感器来实现。
检测树莓派温度代码部分:
import requests
import json
import time
while 1:
try:
file = open("/sys/class/thermal/thermal_zone0/temp")
temp = float(file.read()) / 1000
file.close()
#print "response status: %d" %r.status_code
with open("cpu_result.txt","a") as f:
strTime = time.strftime('%Y-%m-%d:%H-%M-%S',time.localtime(time.time()))
f.write(strTime + " %.1f" %temp + " %d" %r.status_code + "\n")
time.sleep(5*60)
except Exception,e:
with open("cpu_result.txt","a") as f:
f.write("error!\n")
实现后,检测到的温度无法实时查看,需要物联网控制平台yeelink来查看。
综合实现代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
import time
while 1:
try:
file = open("/sys/class/thermal/thermal_zone0/temp")
temp = float(file.read()) / 1000
file.close()
# 设备URI
apiurl = 'http://api.yeelink.net/v1.1/device//sensor/406330/datapoints'
apiheaders = {'U-ApiKey': 'f0f605d2d279ba74edaf0b7a5', 'content-type': 'application/json'}
# 字典类型数据,在post过程中被json.dumps转换为JSON格式字符串 {"value": 48.123}
payload = {'value': temp}
r = requests.post(apiurl, headers=apiheaders, data=json.dumps(payload))
#print "response status: %d" %r.status_code
with open("cpu_result.txt","a") as f:
strTime = time.strftime('%Y-%m-%d:%H-%M-%S',time.localtime(time.time()))
f.write(strTime + " %.1f" %temp + " %d" %r.status_code + "\n")
time.sleep(5*60)
except Exception,e:
with open("cpu_result.txt","a") as f:
f.write("error!\n")
上传成功后,既可以在物联网平台查看。