In this training, you will learn the basics of the Internet of Things. In this part, you will learn how to develop a home security system using a raspberry board and the CherryPy framework.

Picamera program

from picamera import PiCamera

camera = PiCamera()
camera.capture('/home/pi/Pictures/test.jpg')

AHT10 program

import time
import board
import adafruit_ahtx0

# Create sensor object, communicating over the board's default I2C bus
i2c = board.I2C()  # uses board.SCL and board.SDA
sensor = adafruit_ahtx0.AHTx0(i2c)

while True:
    print("\nTemperature: %0.1f C" % sensor.temperature)
    print("Humidity: %0.1f %%" % sensor.relative_humidity)
    time.sleep(2)

Buzzer program

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pin_buzzer= 19
buzzState = False
GPIO.setup(pin_buzzer, GPIO.OUT)
while True:
    buzzState = not buzzState
    GPIO.output(pin_buzzer, buzzState)
    time.sleep(1)

Pushbutton program

import RPi.GPIO as GPIO
from time import sleep

button_PIN = 18

GPIO.setwarnings(False) 
GPIO.setmode(GPIO.BCM)
GPIO.setup(button_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

active_alarme = True

while True:
    buttonState = GPIO.input(button_PIN)
    if buttonState == False :
        active_alarme = not active_alarme
    print(active_alarme)
    sleep(0.5)
    

Motion sensor program

import RPi.GPIO as GPIO
import time
 
GPIO.setmode(GPIO.BCM)
PIR_PIN = 26
GPIO.setup(PIR_PIN, GPIO.IN)

while True:
    if GPIO.input(PIR_PIN):
        print('Motion Detected')
    else:
        print('No Motion Detected')
    time.sleep(1)
    

Template CherryPy

import os, os.path
import cherrypy


class HomeSecurityDashBoard(object):
    @cherrypy.expose
    def index(self):
        return """<html>
          <head>
            <link href="/static/css/style.css" rel="stylesheet">
          </head>
          <body>

          </body>
        </html>"""


if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    cherrypy.quickstart(HomeSecurityDashBoard(), '/', conf)

 

Template home security dashboard 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="refresh" content="2">
        <title>Home Security</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    </head>
    <body>
<section class="vh-100" style="background-color: #C1CFEA;">
  <div class="container py-5 h-100">

    <div class="row d-flex justify-content-center align-items-center h-100" style="color: #282828;">
      <div class="col-md-9 col-lg-7 col-xl-5">

        <div class="card mb-4 gradient-custom" style="border-radius: 25px;">
          <div class="card-body p-4">
          
            <div class="d-flex">
              <h6 class="flex-grow-1">Home security dashboard</h6>
              <h6>15h30</h6>
            </div>
            
             <div class="d-flex flex-column text-center">
              <span style="color: blue; font-size : 25px;">Safe</span>
            </div>
            
             <div class="d-flex align-items-center">
                 <div class="flex-grow-1" style="font-size: 1rem;">
                    <div><i class="bi bi-moisture" style="color: #868B94; font-size : 25px"></i> <span style="font-size : 25px;">40°C</span></div>
                    <div><i class="bi bi-thermometer-half" style="color: #868B94; font-size : 25px"></i> <span style="font-size : 25px;">60%</span> </div>
                 </div>
                 
                <div>
                <span class="dot" style = "height: 45px; width: 45px; background-color: green; border-radius: 50%; display: inline-block;"></span>
                </div>
            
             </div>
            
          </div>
        </div>

        <div class="card mb-4" style="border-radius: 25px;">
          <div class="card-body p-4">
            
            <img src = " " width="100%">

          </div>
        </div>

      </div>
    </div>

  </div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    </body>
</html>

Home security data class 

import time
import board
import adafruit_ahtx0
from datetime import datetime
import RPi.GPIO as GPIO
from picamera import PiCamera

GPIO.setmode(GPIO.BCM)

class HomeSecurityData():
    i2c = board.I2C()  
    sensor = adafruit_ahtx0.AHTx0(i2c)
    motion_PIN = 26
    GPIO.setup(motion_PIN, GPIO.IN)
    buzzer_PIN = 19
    GPIO.setup(buzzer_PIN, GPIO.OUT)
    armed_PIN = 18
    reset_PIN = 5
    GPIO.setup(armed_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(reset_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    camera = PiCamera()
    
    armed = True
    intrude = False
    msg = 'Safe'
    
    def get_weather_condition(self):
        return int(self.sensor.temperature) , int(self.sensor.relative_humidity)
    
    def detect_intruder(self):
        if not self.armed and not self.intrude:
            self.msg = 'Safe'
        elif GPIO.input(self.motion_PIN):
            self.intrude = True
            self.camera.capture('/home/pi/opsa_iot/home_security_dashboard/public/img/intrude.jpg')
            self.msg = "Detected at : " + datetime.now().strftime('%d/%m %H:%M')
        
    def active_buzzer(self):
        if self.intrude and self.armed:
            GPIO.output(self.buzzer_PIN, True)
        else:
            GPIO.output(self.buzzer_PIN, False)
        
    def active_alarme(self):
        buttonState = GPIO.input(self.armed_PIN)
        if buttonState == False:
            self.armed = not self.armed
        
    def reset_system(self):
        buttonState = GPIO.input(self.reset_PIN)
        if buttonState == False:
            self.intrude = False
            
    def main(self):
        self.detect_intruder()
        self.active_alarme()
        self.active_buzzer()
        self.reset_system()
        return self.intrude, self.msg, self.armed
        
if __name__ == "__main__":
    home_date = HomeSecurityData()
    while True:
        intrude, msg = home_date.main()
        temp, hum = home_date.get_weather_condition()
        print(msg)
        print("temperature : %s humidity : %s"%(temp, hum))
        time.sleep(2)

Home security dashboard

import os, os.path
import cherrypy
from home_security_data import HomeSecurityData
from datetime import datetime

class HomeSecurityDashBoard(object):
    
    def __init__(self, security_data):
        self.security_data = security_data
        
    @cherrypy.expose
    def index(self):
        temperature, humidity = self.security_data.get_weather_condition()
        intrude, msg, armed = self.security_data.main()
        image = "/static/img/safe.png"
        alarme = "green"
        localtile = datetime.now().strftime('%d/%m %H:%M')
        if intrude :
            image = "/static/img/intrude.jpg"
        if armed:
            alarme = "red"
        
        return"""
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="refresh" content="1">
        <title>Home Security</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    </head>
    <body>
<section class="vh-100" style="background-color: #C1CFEA;">
  <div class="container py-5 h-100">

    <div class="row d-flex justify-content-center align-items-center h-100" style="color: #282828;">
      <div class="col-md-9 col-lg-7 col-xl-5">

        <div class="card mb-4 gradient-custom" style="border-radius: 25px;">
          <div class="card-body p-4">
          
            <div class="d-flex">
              <h6 class="flex-grow-1">Home security dashboard</h6>
              <h6>"""+localtile+"""</h6>
            </div>
            
             <div class="d-flex flex-column text-center">
              <span style="color: blue; font-size : 25px;">"""+msg+"""</span>
            </div>
            
             <div class="d-flex align-items-center">
                 <div class="flex-grow-1" style="font-size: 1rem;">
                    <div><i class="bi bi-moisture" style="color: #868B94; font-size : 25px"></i> <span style="font-size : 25px;">"""+str(humidity)+"""%</span></div>
                    <div><i class="bi bi-thermometer-half" style="color: #868B94; font-size : 25px"></i> <span style="font-size : 25px;">"""+str(temperature)+"""°C</span> </div>
                 </div>
                 
                <div>
                <span class="dot" style = "height: 45px; width: 45px; background-color: """+alarme+"""; border-radius: 50%; display: inline-block;"></span>
                </div>
            
             </div>
            
          </div>
        </div>

        <div class="card mb-4" style="border-radius: 25px;">
          <div class="card-body p-4">
            
            <img src = " """+image+""" " width="100%">

          </div>
        </div>

      </div>
    </div>

  </div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    </body>
</html>
"""
if __name__ == '__main__':
    security_data = HomeSecurityData()
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    cherrypy.quickstart(HomeSecurityDashBoard(security_data), '/', conf)

 

0 comment

There are no comments yet.

Log in to leave a reply

Related posts

An Internet of Things Training Part 1: Getting Started

13/2/2022

Internet of Things Training Part 2: Programming of Raspberry PI GPIO

13/2/2022

Internet of Things Training Part 3: ThingsBoard IoT platform

14/2/2022