Lab 3 - A Smart Home With 2 Gateways and A Cloud: Nctu Introduction To Iot Fall 2020
Lab 3 - A Smart Home With 2 Gateways and A Cloud: Nctu Introduction To Iot Fall 2020
1
Outline
• Lab Objective
• System Specification
• Topology
• Section 1 – Temperature Monitoring
• Section 2 – Automatic LED
• Section 3 – Intruder Detection
2
Lab Objective
• Simulate the smart home system
• Using 2 Raspberry Pi’s as Gateways
• Connecting 4 types of IoT sensors
• Connecting 3 types of actuators
• Collaborate with MediaTek Cloud Sandbox server (MCS)
• Capable to collaborate more than one Raspberry Pi
• Capable to make the complex IoT system
3
System Specification – Topology
Camera
GPIO19
PIR sensor
2 1
API
API Buzzer
GPIO8
API
GPIO17
GPIO22 GPIO17 GPIO26
GPIO25
GPIO22
Light sensor
Light sensor Relay module LED
DHT sensor
DHT sensor
Fan
4
How to Build it?
5
System Specification – Section 1 (1/4)
2 1 Measure temp/humidity
API
API
by DHT sensors.
Raspberry Pi 1 and 2
GPIO22
GPIO22 send the data to MCS.
1
1st Raspberry Pi API
Relay module
DHT sensor
Fan
7
System Specification – Section 1 (3/4)
1
( Avg Temp > 27˚C ) or ( Avg Humidity > 80% ), API
Relay module
DHT sensor
Fan
8
System Specification – Section 1 (4/4)
9
System Specification – Section 2 (1/3)
GPIO17
GPIO17
Light sensor
LED
Light sensor
10
System Specification – Section 2 (2/3)
1
API
11
System Specification – Section 2 (3/3)
12
System Specification – Section 3 (1/4)
Pi 1
Buzzer
13
System Specification – Section 3 (2/4)
If detected,
Pi 1
give a warning and sends a line notify
GPIO8 Buzzer
14
System Specification – Section 3 (2/4)
MCS Pi 1
Camera
API
15
System Specification – Section 3 (3/3)
Start
Yes
16
System Components
Hardware
Component Name Model Functionality
3x Raspberry Pi 4 Model B, 1 GB RAM Gateway
1x LED Red Visible LED
2x LDR Sensor GL55 Measure the light level
2x Capacitor 1 µF, 50 V Construct RC circuits
3x Resistor 1 kΩ Adjust the voltage
1x PIR sensor HW–416–B Detect the motion
1x Buzzer G-S&S Alarm the intruder
2x DHT sensor AM2302 Measure temp/humidity
2x Fan Raspberry Pi cooling fan Cool down the room
1x Relay module 4–channel 5V Adjust the voltage
1x Camera Raspberry Pi Camera Capture the images
Bread board EIC–1104 Build electronic circuits
Dupont wire Male to Male/Male to Female/Female to Female Construct circuits
17
MCS Dashboard
18
How to Send Notification via Line
• Register at https://notify-
bot.line.me/my/
• Log in by using your Line
account
• Click “Generate Token”
19
MCS Restriction
• Data channel
• Function cannot use the data of other data channels to compute.
• Solution:Retrieves the data, does the computation like average of temp/humidity in
Raspberry.
20
Implementation Photos (1/2)
1st Raspberry Pi
21
Implementation Photos (2/2)
2nd Raspberry Pi
22
1st Raspberry Pi (Source Code) (1/4)
import RPi.GPIO as GPIO sensor = Adafruit_DHT.DHT11
import lineTool pin = 21 #BCM
import time
import http.client, urllib ## Device ID from MCS
import json deviceId = "DkXsnJRf"
import Adafruit_DHT deviceKey = "KUvi9AgEkz9cfEho"
import requests
import socket def linenotify(a,b):
import picamera lineTool.lineNotify(a,b)
from picamera import PiCamera
import numpy as np def play(p, frequency, tempo):
import base64 p.ChangeFrequency(frequency)
time.sleep(0.5 * tempo)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) def bell():
token=”INSERT_YOUR_TOKEN_HERE" C4 = 262 # Do
msg="Intruder detected!" E4 = 330 # Mi
def get_to_mcs(channelID):
host = "http://api.mediatek.com"
endpoint = "/mcs/v2/devices/" + deviceId + "/datachannels/" + channelID +
"/datapoints"
url = host + endpoint
headers = {"Content-type": "application/json", "deviceKey": deviceKey}
r = requests.get(url,headers=headers)
value = (r.json()["dataChannels"][0]["dataPoints"][0]["values"]["value"])
return value
24
1st Raspberry Pi (Source Code) (3/4)
while(True):
## Average Temperature and Humidity then post it to MCS
try:
Temperature_Avg = (temp + Temperature2)/2
## Light Sensor
print ("AVG : ", Temperature_Avg)
LightLevel1 = readLDR(ldrPin)
Humidity2 = get_to_mcs(str(5))
Lightlevel2 = get_to_mcs(str(12))
Humidity_Avg=(humidity+Humidity2)/2
LightAutomation=get_to_mcs(str(9))
payload =
if(LightLevel1-Lightlevel2>0):
{"datapoints":[{"dataChnId":"3","values":{"value":str(Temperatur
Lightlevel_min=Lightlevel2
e_Avg)}},{"dataChnId":"6","values":{"value":str(Humidity_Avg)}}]
else:Lightlevel_min=LightLevel1
}
post_to_mcs(payload)
## Read Temperature 1 and post it to MCS
humidity,temp = Adafruit_DHT.read_retry(sensor, pin)
## FANControl 1
payload =
if (get_to_mcs(str(7)) == 1):
{"datapoints":[{"dataChnId":"4","values":{"value":humidity}},{"dataChn
get_to_mcs(str(7))
Id":"1","values":{"value":temp}},{"dataChnId":"11","values":{"value":s
turnonFAN(fan_pin)
tr(LightLevel1)}}]}
post_to_mcs(payload)
elif(get_to_mcs(str(7)) == 0):
turnoffFAN(fan_pin)
if(LightAutomation==1):
print("Light automation activates.")
## FANControl 2
PWM_LED(Lightlevel_min)
if (get_to_mcs(str(8)) == 1):
turnonFAN(fan_pin2)
else:
elif(get_to_mcs(str(8)) == 0):
print("Light automation deactivates.")
turnoffFAN(fan_pin2)
PWM_LED(0)
## Read Temperature 2
Temperature2 = get_to_mcs(str(2))
print ("Debug Temp : ", Temperature2)
25
1st Raspberry Pi (Source Code) (4/4)
# PIR Setup
i=GPIO.input(PIR_pin)
if(i==0):
print("No intruder.")
time.sleep(2)
elif(i==1):
print("Intruder detected.")
linenotify(token,msg)
camera = PiCamera()
camera.resolution = (720,480)
camera.start_preview()
camera.capture('intruder.jpg')
camera.stop_preview()
with open("intruder.jpg","rb") as img_file:
EncodeBytes = base64.b64encode(img_file.read())
EncodeStr = str(EncodeBytes, "utf-8")
payload = {"datapoints":[{"dataChnId":"20","values":{"value":EncodeStr}}]}
post_to_mcs(payload)
bell()
time.sleep(2)
except KeyboardInterrupt:
break
GPIO.cleanup()
26
2nd Raspberry Pi (Source Code)
# Import Libraries # Set MediaTek Cloud Sandbox (MCS) Connection
import time def post_to_mcs(payload):
import http.client, urllib headers = {"Content-type": "application/json", "deviceKey":
import json deviceKey}
import Adafruit_DHT not_connected = 1
import RPi.GPIO as GPIO while (not_connected):
import requests try:
Import socket conn = http.client.HTTPConnection("api.mediatek.com:80")
conn.connect()
not_connected = 0
# Set Pin for Sensors except (http.client.HTTPException, socket.error) as ex:
#LDR print ("Error: %s" % ex)
GPIO.setmode(GPIO.BOARD) time.sleep(10) # sleep 10 seconds
GPIO.setwarnings(False)
conn.request("POST", "/mcs/v2/devices/" + deviceId +
ldrPin = 36 "/datapoints", json.dumps(payload), headers)
response = conn.getresponse()
sensor = Adafruit_DHT.DHT11 print( response.status, response.reason, json.dumps(payload),
pin = 21 time.strftime("%c"))
data = response.read()
# Set MediaTek Cloud Sandbox (MCS) Key conn.close()
deviceId = ”YOUR_DEVICE_ID"
deviceKey = ”YOUR_DEVICE_KEY" # Post MediaTek Cloud Sandbox (MCS)
while True:
# Set Function for Reading LDR [humidity,temp] = Adafruit_DHT.read_retry(sensor, pin)
def readLDR(PIN): print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))
reading=0 ldr_reading = readLDR(ldrPin)
GPIO.setup(PIN, GPIO.OUT) print("LDR : ", ldr_reading)
GPIO.output(PIN, False) payload =
time.sleep(0.1) {"datapoints":[{"dataChnId":"5","values":{"value":humidity}},{"dataChn
GPIO.setup(PIN, GPIO.IN) Id":"2","values":{"value":temp}},{"dataChnId":"12","values":{"value":s
while (GPIO.input(PIN)==False): tr(ldr_reading)}}]}
reading=reading+1 post_to_mcs(payload) 27
return reading time.sleep(5)
Assignment 3 - Specification
• Objectives:
• IoT with Complex Sensors and Actuators
• Collaborate 2 Raspberry Pi’s with MCS
• Upload to E3 before 12/21 (Mon) at 23:59PM
• Assignment 3 – deliverables
• Report (2-4 pages)
• Explain the objectives
• Explain the specification of sensors and actuators used
• Explain the system design
• Flowchart of your system
• Explain your python and javascript source codes
• The differences with example codes
• The detail of how your scripts work
• Source Codes
• 3~5-minute demo video (just the URL of video)
• Report can be written in Chinese, and for Video, it must be delivered in English or with English
Caption
• Zip the above files into one compressed file and upload
• Q&A? Post on E3 discussion board
28
Thank You
29