获取树莓派cpu温度上传yeeklink

本文介绍了一个使用Python脚本持续监测树莓派CPU温度并将其上传至Yeelink云平台的项目。脚本每5分钟读取一次温度数据,并通过HTTP POST请求发送到远程服务器。同时记录了如何设置脚本随系统启动自动运行,以及如何检查数据上传状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值