与 IoT 相关的云端服务为数众多,例如:ThingSpeak、WoT.City、AWS、IBM Bluemix、MediaTek MCS、Google Firebase 等,并在透过这些云端服务可在对数据进行数据可视化、数据分析与其它的应用,而本文用Python将透过 Raspberry Pi 采集到的温湿度信息传送到 AWS IoT。
情境
材料与准备
1.准备 Raspberry Pi 3Model B 开发板
2.准备 Micro SD (已安装 Raspbian)
3.将 Micro SD 装入到 RaspberryPi 中
4.设定好网络
5.安装 GrovePi+
6.安装 Grove – Temperatureand Humidity Sensor (D4)
7.安装 GROVE - LCD RGBBACKLIGHT (I2C-2)
8.安装 IDE ( Sublime Textor Visual Studio Code )
Sensor, LCD, GrovePi+ 与 RaspberryPi 连接如下图
AWS IoT 端
Step 1. 到 AWS 网站申请账号
Step 2. 登入 AWS 网站
Step 3. 点击 Services AWS IoT
Step 4. 点击 Create a resource
Step 5. 点击 Create a thing 输入 thing Name Create
Step 6. 点击刚建立的 thing
Step 7. 点击 Connect a device
Step 8. 点击 Node.js Generate certificate and policy
Step 9. 下载 private 与 public keys
Step 10. 点击 Confirm &connecting
Step 11. 点击 Return to ThingDetail
Raspberry Pi 端
Step 1. 透过 Python 读取温湿度信息并传送到AWS IoT
#****************************************************
# Import Package
#****************************************************
import time
import datetime
import paho.mqtt.client as paho
import json
import ssl
import sys
sys.path.append('/home/pi/rpi/code/Package')
import grovepi
from grove_rgb_lcd import *
#****************************************************
# Set Pin No, AWS Config
#****************************************************
sensor = 4
blue = 0 # The Blue colored sensor.
white = 1 # The White colored sensor.
connflag = False
#****************************************************
# Set AWS Connection
#****************************************************
def on_connect(client, userdata, flags,rc):
global connflag
connflag = True
print("Connection returned result: " + str(rc) )
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
mqttc = paho.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
awshost = "a3iprlpgye4dmu.iot.us-west-2.amazonaws.com"
awsport = 8883
clientId = "sensorData"
thingName = "sensorData"
caPath = "./root-CA.crt"
certPath ="./000cd28455-certificate.pem.crt"
keyPath = "./000cd28455-private.pem.key"
mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath,cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
mqttc.connect(awshost, awsport, keepalive=60)
mqttc.loop_start()
#****************************************************
# Publish AWS
#****************************************************
while True:
[temp,humidity] = grovepi.dht(sensor,blue)
print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))
t= time.time();
date = datetime.datetime.fromtimestamp(t).strftime('%Y%m%d%H%M%S')
if connflag == True:
mqttc.publish("topic/sensorData",json.dumps({"time": date, "temperature": temp,"humidity": humidity}), qos=1)
else:
print("waiting for connection...")
time.sleep(1)
Step 2. 将 Python Code 与 Keys 传送到 RaspberryPi
Step 3. 执行刚传到 Raspberry Pi 中的 Python 代码,python 檔名.py
Step 4. Console 执行画面
作者:Archer Huang
全部0条评论
快来发表一下你的评论吧 !