好记性不如铅笔头

linux, 操作系统, 树莓派

树莓派学习笔记:将温度上传yeelink

根据前面的两篇笔记,我们就可以实现将温度自动上传到yeelink的功能。这里简单的备份下代码吧。

参考

http://116.62.110.235/blog/raspberry-pie-study-notes-use-of-ds18b20-temperature-sensor-for-measuring-temperature/ 】

http://116.62.110.235/blog/yeelink-note-registration-and-api/ 】

这里新建一个传感器,ID为12974,将温度传感器连接到树莓派上之后,我们就可以运行这个python脚本了,

需要注意的是作者的树莓派的版本为 【 3.2.3 】,里面的 【 urllib.request.Request();】构造函数和【 3.3.4 】不同,需要修改下之前的脚本才可以。

import urllib.request
import re;

def addKeyToHeader(req):
	req.add_header("U-ApiKey","xxxx");
	
def httpPost(str, data):
	req = urllib.request.Request(str);
	addKeyToHeader(req);
	req.data = data.encode(encoding="utf-8");
	r = urllib.request.urlopen(req);
	print(data);
	
if __name__ == "__main__":
	print("GetTempture:");
	fp=open("/sys/bus/w1/devices/28-00000396afcb/w1_slave","r");
	alllines=fp.readlines();
	fp.close();
	tempture = re.search(r"t=[0-9]{3,}", alllines[1]);
	tempture = tempture.group(0);
	tempture = tempture[2:];
	httpPost("http://api.yeelink.net/v1.0/device/8060/sensor/12794/datapoints","{\"value\":" + str(int(tempture)/1000) + "}");

 运行方法:

pi@raspberrypi ~ $ python3 UploadTempture.py 
GetTempture:
{"value":19.062}

yeelink截图如下:

由于作者的树莓派不是一直连接电源,而且温度传感器也不是一直连接到树莓派上的,就不进行定时任务了,如果要进行定时任务,可以参考笔记 【 http://116.62.110.235/blog/common-commands-for-linux-backups-crontab/ 】

发表评论

11 − 6 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据