Raspberry - 監控CPU溫度[使用yeelink作溫度統計]

1. 獲取CPU溫度,將該溫度上傳至yeelink的python腳本(我的保存位置:~/program/python/upload_temperature_cron.py)

#!/usr/bin/python
#coding=utf-8

"""獲取樹莓派的溫度,並上傳到yeelink"""

import commands
import requests
import json
from time import strftime, sleep

headers = {"U-ApiKey": "XXX"}
DEVICE_ID = "XXX"
CPU_SENSOR_ID = "XXX"

def upload_temp(sensor_type, temp):
    if sensor_type == "cpu":
        sensor_id = CPU_SENSOR_ID
        print "CPU Temp:", temp
    else:
        sensor_id = GPU_SENSOR_ID
        print "GPU Temp:", temp
    url = r"http://api.yeelink.net/v1.0/device/%s/sensor/%s/datapoints" % (DEVICE_ID, sensor_id)
    #print url
    data = {"timestamp": strftime("%Y-%m-%dT%H:%M:%S"), "value": temp}
    #print data
    r = requests.post(url, data=json.dumps(data), headers=headers)

def get_cpu_temp():
    tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
    cpu_temp = tempFile.read()
    tempFile.close()
    return float(cpu_temp)/1000

upload_temp("cpu", get_cpu_temp())
(腳本基於:https://github.com/virusdefender/MyRasPi/blob/master/temperature.py 修改)

2. 獲取 U-ApiKey & DEVICE_ID & CPU_SENSOR_ID。

獲取方法:http://www.yeelink.net/ 註冊完賬號後進入用戶中心,在賬戶->我的賬戶設置中找到API KEY。

在我的設備->增加新設備中增加一個設備,然後切換到管理設備,增加一個傳感器。增加成功後,會看到一個類似這樣的URL:http://api.yeelink.net/v1.0/device/12020/sensor/19995/datapoints,這個URL爲API地址,該url中的12020爲腳本中的DEVICE_ID,19995爲CPU_SENSOR_ID。


3. 將該腳本加入crontab,每分鐘運行一次。

crontab -e

添加 * * * * * /usr/bin/python ~/program/python/upload_temperature_cron.py >> ~/program/python/upload_temperature.output 到最後一行,保存退出

sudo /etc/init.d/cron restart


查看溫度數據可以去yeelink用戶中心,我的設備->管理設備中剛纔添加傳感器的地方查看。也可以直接訪問:http://www.yeelink.net/devices/12020(將12020換成你的DEVICE_ID)。另,在~/program/python/upload_temperature.output 中會有所有溫度數據的記錄,也可直接從這裏查看。

發佈了83 篇原創文章 · 獲贊 26 · 訪問量 73萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章