這裏選取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