用树莓派搭建简单的传感器物联网应用

这里选取DS18B20做为温度传感器,该传感器使用单总线链接至树莓派。本例将采集到的温度数据同时上传乐为物联Yeelink两个IoT云端平台.python

1. 挂载DS18B20git

sudo modprobe w1-gpio
sudo modprobe w1-therm

2. 安装Python的库单总线温度计访问库: w1thermsensorgithub

pip install w1thermsensor

3. 新建一个iot.py文件敲入如下代码json

#!/usr/bin/env python
#coding=utf8

import httplib, urllib

from w1thermsensor import W1ThermSensor
import time
import socket, serial, time
import httplib
import json

HOST = "open.lewei50.com"

PORT = 80
 

user_key = '乐为物联的userkey'

def send_data_to_yeelink(temp):

		httpClient = None
		try:
			params = json.dumps({'value': temp})
			headers = {"Content-type": "application/json"
                    , "Accept": "text/plain",'U-ApiKey': 'Yeelink的api key'}
 
			print params
			httpClient = httplib.HTTPConnection('api.yeelink.net', 80, timeout=30)
			httpClient.request("POST", "/v1.1/device/设备id/sensor/传感器id/datapoints", params, headers)
 
			response = httpClient.getresponse()
			print response.status
			print response.reason
			print response.read()
			print response.getheaders() #获取头信息
		except Exception, e:
			print e
		finally:
			if httpClient:
				httpClient.close()
 

def send_data(temp):

		httpClient = None
		try:
			params = json.dumps([{'Name': '传感器名称', 'Value': temp}])
			headers = {"Content-type": "application/x-www-form-urlencoded"
                    , "Accept": "text/plain","userkey":user_key}
 
			print params
			httpClient = httplib.HTTPConnection(HOST, 80, timeout=30)
			httpClient.request("POST", "/api/V1/Gateway/UpdateSensors/01", params, headers)
 
			response = httpClient.getresponse()
			print response.status
			print response.reason
			print response.read()
			print response.getheaders() #获取头信息
		except Exception, e:
			print e
		finally:
			if httpClient:
				httpClient.close()
while True:
	for sensor in W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18B20]):
		temp=sensor.get_temperature()
		print("Sensor %s has temperature %.2f" % (sensor.id,temp ))
		send_data(temp)
		send_data_to_yeelink(temp)
	time.sleep(120)

4. 运行python脚本api

python iot.py

5. 若是温度读取成功且上传成功会打印相关消息.bash

相关文章
相关标签/搜索