#!/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.0/device/344133/sensor/383211/datapoints'
apiheaders = {'U-ApiKey': 'cfcaf1bbcff8559b6f1e9ba2ed3b219a', '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")
开机启动:
vim auto-start-cpu.sh
#!/bin/bash
cd /home/pi/alex/code/
python cpu.py &
sudo chmod a+x auto-start-cpu.sh
sudo vim /etc/rc.local 在exit 0前加上
/home/pi/alex/code/auto-start-cpu.sh start
exit 0
ps aux | grep cpu.py 可以查看进程
pi@raspberrypi:~/alex/code $ ps aux | grep cpu.py
pi 1462 7.0 1.4 16288 12616 pts/0 S 21:57 0:00 python cpu.py
pi 1468 0.0 0.2 4276 1848 pts/0 S+ 21:57 0:00 grep --color=auto cpu.py
kill -s 9 2389 可以杀掉进程
检查是否已经上传:vim curl_yeelink.sh
#!/bin/bash
curl --request GET --header "U-ApiKey:cfcaf1bbcff8559b6f1e9ba2ed3xxxa" http://api.yeelink.net/v1.0/device/344133/sensor/383211/datapoints
pi@raspberrypi:~/alex/code/cpu_temp $ ./curl_yeelink.sh
{"timestamp":"2016-04-04T01:02:48","value":38.628}