lab 3 -a smart home with 2 gateways and a cloud

29
NCTU introduction to IoT Fall 2020 1 Lab 3 - A Smart Home with 2 Gateways and a Cloud

Upload: others

Post on 21-Oct-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lab 3 -A Smart Home with 2 Gateways and a Cloud

NCTU introduction to IoTFall 2020

1

Lab 3 - A Smart Home with 2 Gateways and a Cloud

Page 2: Lab 3 -A Smart Home with 2 Gateways and a Cloud

Outline

• Lab Objective• System Specification • Topology• Section 1 – Temperature Monitoring• Section 2 – Automatic LED• Section 3 – Intruder Detection

2

Page 3: Lab 3 -A Smart Home with 2 Gateways and a Cloud

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

Page 4: Lab 3 -A Smart Home with 2 Gateways and a Cloud

System Specification – Topology

4

12

DHT sensorDHT sensor

Light sensor

Light sensor

Fan

Relay module LED

Buzzer

PIR sensor

GPIO17GPIO22

API

API

GPIO22GPIO26 GPIO25

GPIO17

GPIO8

GPIO19

API

Camera

Page 5: Lab 3 -A Smart Home with 2 Gateways and a Cloud

How to Build it?

Section 1:Temperature/Humidity too high → Turn on the fan.

Section 2: Brightness in the room → Luminates the LED.

Section 3: Intruder detected → Send a Line Notification + Play the

buzzer + Capture a photo.

5

Page 6: Lab 3 -A Smart Home with 2 Gateways and a Cloud

6

12

DHT sensorDHT sensor

Fan

Relay module

GPIO22

API

API

GPIO22

System Specification – Section 1 (1/4)

Measure temp/humidity

by DHT sensors.

Raspberry Pi 1 and 2

send the data to MCS.

Page 7: Lab 3 -A Smart Home with 2 Gateways and a Cloud

7

1

DHT sensor

Fan

Relay module

API

System Specification – Section 1 (2/4)

1st Raspberry Pi

retrieves the data from 2nd Raspberry Pi,

calculates the average,

sends back to MCS.

Page 8: Lab 3 -A Smart Home with 2 Gateways and a Cloud

8

1

DHT sensor

Fan

Relay module

API

System Specification – Section 1 (3/4)

GPIO26

( Avg Temp > 27˚C ) or ( Avg Humidity > 80% ),

MCS sets on the Fancontrol data channel.

1st Raspberry Pi receives the signal,

turns on the fan through relay module.

Page 9: Lab 3 -A Smart Home with 2 Gateways and a Cloud

9

System Specification – Section 1 (4/4)

Page 10: Lab 3 -A Smart Home with 2 Gateways and a Cloud

10

System Specification – Section 2 (1/3)

Measure light level

by light sensors.

1st and 2nd Raspberry Pi

send the data to MCS.

Click on the LightAutomation

button on MCS to start.12

API API

GPIO17GPIO17

Light sensorLight sensorLED

Page 11: Lab 3 -A Smart Home with 2 Gateways and a Cloud

11

1

System Specification – Section 2 (2/3)

1st Raspberry Pi retrieves the data of

2nd Raspberry Pi, chooses the darker

one’s value, modulates the luminance

of LED.Light sensorLED

API

GPIO25

Page 12: Lab 3 -A Smart Home with 2 Gateways and a Cloud

12

System Specification – Section 2 (3/3)

Page 13: Lab 3 -A Smart Home with 2 Gateways and a Cloud

13

Pi 1

Buzzer

PIR sensorGPIO19

System Specification – Section 3 (1/4)

This alarm system keeps running.

Detect an intruder by PIR sensor.

Page 14: Lab 3 -A Smart Home with 2 Gateways and a Cloud

14

System Specification – Section 3 (2/4)

If detected,

1st Raspberry Pi plays the buzzer to

give a warning and sends a line notify

to the owner immediately.Buzzer

PIR sensor

API

GPIO8

Pi 1

Page 15: Lab 3 -A Smart Home with 2 Gateways and a Cloud

15

System Specification – Section 3 (2/4)

Then, 1st Raspberry Pi captures the

image from Camera and send it into

MCS

PIR sensor

API

Pi 1

Camera

Page 16: Lab 3 -A Smart Home with 2 Gateways and a Cloud

16

System Specification – Section 3 (3/3)

IntruderDetected

RaspberryPi1sendsLineNotificationthroughLineAPI

Start

RaspberryPi1playsthebuzzer

RaspberryPi1capturesthephoto,thensendittoMCS

Yes

No Sleepfor2s

Page 17: Lab 3 -A Smart Home with 2 Gateways and a Cloud

17

System ComponentsHardware

Component Name Model Functionality3x 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

Page 18: Lab 3 -A Smart Home with 2 Gateways and a Cloud

18

MCS Dashboard

Page 19: Lab 3 -A Smart Home with 2 Gateways and a Cloud

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

Page 20: Lab 3 -A Smart Home with 2 Gateways and a Cloud

20

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.

• ”Bad Access” if query too often• Solution:Raspberry Pi sends the measured data all at once every 30 seconds.

Page 21: Lab 3 -A Smart Home with 2 Gateways and a Cloud

Implementation Photos (1/2)

21

1st Raspberry Pi

Page 22: Lab 3 -A Smart Home with 2 Gateways and a Cloud

22

Implementation Photos (2/2)2nd Raspberry Pi

Page 23: Lab 3 -A Smart Home with 2 Gateways and a Cloud

1st Raspberry Pi (Source Code) (1/4)

23

import RPi.GPIO as GPIOimport lineToolimport timeimport http.client, urllibimport jsonimport Adafruit_DHTimport requestsimport socketimport picamerafrom picamera import PiCameraimport numpy as npimport base64

GPIO.setwarnings(False)GPIO.setmode(GPIO.BOARD)token=”INSERT_YOUR_TOKEN_HERE"msg="Intruder detected!"

PIR_pin=35GPIO.setup(PIR_pin,GPIO.IN)

ledPin = 22ldrPin = 12GPIO.setup(ledPin,GPIO.OUT)

fan_pin = 37fan_pin2 = 36GPIO.setup(fan_pin, GPIO.OUT)GPIO.setup(fan_pin2, GPIO.OUT)

PWM_FREQ=200pwm=GPIO.PWM(ledPin,PWM_FREQ)pwm.start(0) #Start control PWM and initialize to 0

sensor = Adafruit_DHT.DHT11pin = 21 #BCM

## Device ID from MCSdeviceId = "DkXsnJRf"deviceKey = "KUvi9AgEkz9cfEho"

def linenotify(a,b):lineTool.lineNotify(a,b)

def play(p, frequency, tempo):p.ChangeFrequency(frequency)time.sleep(0.5 * tempo)

def bell():C4 = 262 # DoE4 = 330 # Mi

music = [C4, E4]M_1 = C4M_3 = E4

GPIO.setup(24, GPIO.OUT)p = GPIO.PWM(24, 50)p.start(15) # 0 <= DV <= 100

play(p, M_3, 1)play(p, M_1, 1)

p.stop

Page 24: Lab 3 -A Smart Home with 2 Gateways and a Cloud

1st Raspberry Pi (Source Code) (2/4)

24

# Set MediaTek Cloud Sandbox (MCS) Connection def post_to_mcs(payload):

headers = {"Content-type": "application/json", "deviceKey": deviceKey}not_connected = 1while (not_connected):

try:conn = http.client.HTTPConnection("api.mediatek.com:80")conn.connect()not_connected = 0

except (http.client.HTTPException, socket.error) as ex:print ("Error: %s" % ex)time.sleep(10) # sleep 10 seconds

conn.request("POST", "/mcs/v2/devices/" + deviceId + "/datapoints", json.dumps(payload), headers)

response = conn.getresponse()#print( response.status, response.reason, json.dumps(payload),

time.strftime("%c"))data = response.read()conn.close()

def get_to_mcs(channelID):host = "http://api.mediatek.com"endpoint = "/mcs/v2/devices/" + deviceId + "/datachannels/" + channelID +

"/datapoints"url = host + endpointheaders = {"Content-type": "application/json", "deviceKey": deviceKey}r = requests.get(url,headers=headers)value = (r.json()["dataChannels"][0]["dataPoints"][0]["values"]["value"])return value

def readLDR(PIN):reading=0GPIO.setup(PIN, GPIO.OUT)GPIO.output(PIN, False)time.sleep(0.1)GPIO.setup(PIN, GPIO.IN)while (GPIO.input(PIN)==False):

reading=reading+1return reading

def PWM_LED(lightlevel):duty_cycle=lightlevel/100 #duty_cycle:0~100if(duty_cycle>=100):duty_cycle=100pwm.ChangeDutyCycle(duty_cycle)

def turnonFAN(fan_input):GPIO.output(fan_input, False)

def turnoffFAN(fan_input):GPIO.output(fan_input, True)

Page 25: Lab 3 -A Smart Home with 2 Gateways and a Cloud

1st Raspberry Pi (Source Code) (3/4)

25

while(True):try:

## Light SensorLightLevel1 = readLDR(ldrPin)Lightlevel2 = get_to_mcs(str(12))LightAutomation=get_to_mcs(str(9))

if(LightLevel1-Lightlevel2>0):Lightlevel_min=Lightlevel2

else:Lightlevel_min=LightLevel1

## Read Temperature 1 and post it to MCShumidity,temp = Adafruit_DHT.read_retry(sensor, pin)payload =

{"datapoints":[{"dataChnId":"4","values":{"value":humidity}},{"dataChnId":"1","values":{"value":temp}},{"dataChnId":"11","values":{"value":str(LightLevel1)}}]}

post_to_mcs(payload)

if(LightAutomation==1):print("Light automation activates.")PWM_LED(Lightlevel_min)

else:print("Light automation deactivates.")PWM_LED(0)

## Read Temperature 2Temperature2 = get_to_mcs(str(2))print ("Debug Temp : ", Temperature2)

## Average Temperature and Humidity then post it to MCSTemperature_Avg = (temp + Temperature2)/2print ("AVG : ", Temperature_Avg)Humidity2 = get_to_mcs(str(5))Humidity_Avg=(humidity+Humidity2)/2

payload = {"datapoints":[{"dataChnId":"3","values":{"value":str(Temperature_Avg)}},{"dataChnId":"6","values":{"value":str(Humidity_Avg)}}]}

post_to_mcs(payload)

## FANControl 1if (get_to_mcs(str(7)) == 1):get_to_mcs(str(7))

turnonFAN(fan_pin)

elif(get_to_mcs(str(7)) == 0):turnoffFAN(fan_pin)

## FANControl 2if (get_to_mcs(str(8)) == 1):

turnonFAN(fan_pin2)elif(get_to_mcs(str(8)) == 0):

turnoffFAN(fan_pin2)

Page 26: Lab 3 -A Smart Home with 2 Gateways and a Cloud

1st Raspberry Pi (Source Code) (4/4)

26

# PIR Setupi=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()

Page 27: Lab 3 -A Smart Home with 2 Gateways and a Cloud

2nd Raspberry Pi (Source Code)

27

# Import Librariesimport timeimport http.client, urllibimport jsonimport Adafruit_DHTimport RPi.GPIO as GPIOimport requestsImport socket

# Set Pin for Sensors#LDRGPIO.setmode(GPIO.BOARD)GPIO.setwarnings(False)

ldrPin = 36

sensor = Adafruit_DHT.DHT11pin = 21

# Set MediaTek Cloud Sandbox (MCS) Key deviceId = ”YOUR_DEVICE_ID"deviceKey = ”YOUR_DEVICE_KEY"

# Set Function for Reading LDRdef readLDR(PIN):

reading=0GPIO.setup(PIN, GPIO.OUT)GPIO.output(PIN, False)time.sleep(0.1)GPIO.setup(PIN, GPIO.IN)while (GPIO.input(PIN)==False):

reading=reading+1return reading

# Set MediaTek Cloud Sandbox (MCS) Connection def post_to_mcs(payload):

headers = {"Content-type": "application/json", "deviceKey": deviceKey}

not_connected = 1while (not_connected):

try:conn = http.client.HTTPConnection("api.mediatek.com:80")conn.connect()not_connected = 0

except (http.client.HTTPException, socket.error) as ex:print ("Error: %s" % ex)time.sleep(10) # sleep 10 seconds

conn.request("POST", "/mcs/v2/devices/" + deviceId + "/datapoints", json.dumps(payload), headers)

response = conn.getresponse()print( response.status, response.reason, json.dumps(payload),

time.strftime("%c"))data = response.read()conn.close()

# Post MediaTek Cloud Sandbox (MCS) while True:

[humidity,temp] = Adafruit_DHT.read_retry(sensor, pin)print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))ldr_reading = readLDR(ldrPin)print("LDR : ", ldr_reading)payload =

{"datapoints":[{"dataChnId":"5","values":{"value":humidity}},{"dataChnId":"2","values":{"value":temp}},{"dataChnId":"12","values":{"value":str(ldr_reading)}}]}

post_to_mcs(payload)time.sleep(5)

Page 28: Lab 3 -A Smart Home with 2 Gateways and a Cloud

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 board28

Page 29: Lab 3 -A Smart Home with 2 Gateways and a Cloud

Thank You

29