2021-L3-Galilee-IoT- 2020 home surveillance

A house autonomous surveillance system that notify the owner whenever it detects any sort of movements and trigger a sound alarm in the absence of the owner's feedback.

Slides & Videos

Members

NameContribution
Abdel Mounaim BOUZERIRA=>Live stream camera to browser
=>Motion detection
=>User notification via Email
=> Etude technique du system
Marwane GHARS=>Alarm sonore
=> Lecture d'empreinte
=> Etude technique du system
=> Etude de marché

State of the Art

Technical Aspect

Project Description

Problem Definition
Private property security
Challenges & Motivation
Since security has become something crucial nowadays we decided to build an affordable home security system that can can be used in any type of private property .
The main challenge was to find a way of communicating different processes between each other and exchanging information about the collected data .
Real and Complete Usecases

 

 The sytem is continuously
proccessing its environment , and when a object is close enough
the system begin a live stream , if the system does recognize the
owner using the fingerprint device he will receive an email wich
contains an image of the detected object as well as a link to the
camera live stream , the owner than will have the choise to trigger
an alarm or discard the the warning , in the absence of any
feedback the alarm will be trigged any way.

Technical Description

The system is a combination of :

  • Raspberry pi 3 model B+
  • 2 picameras modules 
  • 2 HC_SR04 motion sensors 
  • Finger print reader 
  • USB to TTL convertor that links the finger print sensor to the raspberry

=> The outdoor camera is responsible for sending a picture  of whenever a object is detected with the help of the motion detector via an email notification 

=> The indoor camera is responsible of live streaming the events   inside the owner’s property in case the person that made inside is detected by the second motion detector and  didn’t not identify him self  using the finger print module 

Hardware

Materials
ImageNamePart NumberPriceCountLink
hc-sr04.42🛒
picamera.12.992🛒
fingerprint module.201🛒
raspberry pi 3 b+.601🛒
Schematic

Software

Arduino Code

from gpiozero import Buzzer
from time import sleep

buzzer = Buzzer(26)

while True:
    buzzer.on()
    sleep(1)
    buzzer.off()
    sleep(1)
import RPi.GPIO as GPIO
from time import sleep
import os 
from multiprocessing import Process
import smtplib
import imghdr
from email.message import EmailMessage

#lunch the buzzer script
def alarm():
    os.system("python3 buzzer.py")

# lunch the stream script 
def stream():
    os.system("python3 stream.py")



# Email settings 
sender = os.environ.get('EMAIL_USER')
password = os.environ.get('EMAIL_PASS')
message="SECURITY ALERT !! "

content="""\

Click HERE to see the live stream

Click

# Web streaming example
# Source code from the official PiCamera package
# http://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming

import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\


Raspberry Pi - Surveillance Camera


Raspberry Pi - Surveillance Camera

""" class StreamingOutput(object): def __init__(self): self.frame = None self.buffer = io.BytesIO() self.condition = Condition() def write(self, buf): if buf.startswith(b'\xff\xd8'): # New frame, copy the existing buffer's content and notify all # clients it's available self.buffer.truncate() with self.condition: self.frame = self.buffer.getvalue() self.condition.notify_all() self.buffer.seek(0) return self.buffer.write(buf) class StreamingHandler(server.BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.send_response(301) self.send_header('Location', '/index.html') self.end_headers() elif self.path == '/index.html': content = PAGE.encode('utf-8') self.send_response(200) self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(content)) self.end_headers() self.wfile.write(content) elif self.path == '/stream.mjpg': self.send_response(200) self.send_header('Age', 0) self.send_header('Cache-Control', 'no-cache, private') self.send_header('Pragma', 'no-cache') self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME') self.end_headers() try: while True: with output.condition: output.condition.wait() frame = output.frame self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') self.send_header('Content-Length', len(frame)) self.end_headers() self.wfile.write(frame) self.wfile.write(b'\r\n') except Exception as e: logging.warning( 'Removed streaming client %s: %s', self.client_address, str(e)) else: self.send_error(404) self.end_headers() class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): allow_reuse_address = True daemon_threads = True with picamera.PiCamera(resolution='640x480', framerate=24) as camera: output = StreamingOutput() #Uncomment the next line to change your Pi's Camera rotation (in degrees) #camera.rotation = 90 camera.start_recording(output, format='mjpeg') try: address = ('', 8000) server = StreamingServer(address, StreamingHandler) server.serve_forever() finally: camera.stop_recording()
# source https://github.com/e-tinkers

import RPi.GPIO as GPIO
import os
from time import sleep
from http.server import BaseHTTPRequestHandler, HTTPServer

host_name = "192.168.36.143"  # Change this to your Raspberry Pi IP address
host_port = 7000



class MyServer(BaseHTTPRequestHandler):
    """ A special implementation of BaseHTTPRequestHander for reading data from
        and control GPIO of a Raspberry Pi
    """

    def do_HEAD(self):
        """ do_HEAD() can be tested use curl command
            'curl -I http://server-ip-address:port'
        """
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def _redirect(self, path):
        self.send_response(303)
        self.send_header('Content-type', 'text/html')
        self.send_header('Location', path)
        self.end_headers()

    def do_GET(self):
        """ do_GET() can be tested using curl command
            'curl http://server-ip-address:port'
        """
        html = """
           
           
           

Turn On/Off your alarm

Turn LED :
""" temp = os.popen("/opt/vc/bin/vcgencmd measure_temp").read() self.do_HEAD() self.wfile.write(html.format(temp[5:]).encode("utf-8")) def do_POST(self): """ do_POST() can be tested using curl command 'curl -d "submit=On" http://server-ip-address:port' """ content_length = int(self.headers['Content-Length']) # Get the size of data post_data = self.rfile.read(content_length).decode("utf-8") # Get the data post_data = post_data.split("=")[1] # Only keep the value # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) # Trigger the alarm if post_data == "On": os.system("python3 buzzer.py") #KIll the process 'buzzer.py' else: for line in os.popen("ps ax | grep buzzer | grep -v grep"): fields = line.split() # extracting Process ID from the output pid = fields[0] # terminating process os.kill(int(pid), signal.SIGKILL) print("LED is {}".format(post_data)) self._redirect('/') # Redirect back to the root url if __name__ == "__main__": http_server = HTTPServer((host_name, host_port), MyServer) print("Server Starts - %s:%s" % (host_name, host_port)) try: http_server.serve_forever() except KeyboardInterrupt: http_server.server_close()
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke 
All rights reserved.
"""

import time
from pyfingerprint.pyfingerprint import PyFingerprint


## Enrolls new finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to enroll new finger
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 1
    f.convertImage(0x01)

    ## Checks if finger is already enrolled
    result = f.searchTemplate()
    positionNumber = result[0]

    if ( positionNumber >= 0 ):
        print('Template already exists at position #' + str(positionNumber))
        exit(0)

    print('Remove finger...')
    time.sleep(2)

    print('Waiting for same finger again...')

    ## Wait that finger is read again
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 2
    f.convertImage(0x02)

    ## Compares the charbuffers
    if ( f.compareCharacteristics() == 0 ):
        raise Exception('Fingers do not match')

    ## Creates a template
    f.createTemplate()

    ## Saves template at new position number
    positionNumber = f.storeTemplate()
    print('Finger enrolled successfully!')
    print('New template position #' + str(positionNumber))

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
PyFingerprint
Copyright (C) 2015 Bastian Raschke 
All rights reserved.
"""

import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint


## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 1
    f.convertImage(0x01)

    ## Searchs template
    result = f.searchTemplate()

    positionNumber = result[0]
    accuracyScore = result[1]

    if ( positionNumber == -1 ):
        print('No match found!')
        exit(0)
    else:
        print('Found template at position #' + str(positionNumber))
        print('The accuracy score is: ' + str(accuracyScore))

    ## OPTIONAL stuff
    ##

    ## Loads the found template to charbuffer 1
    f.loadTemplate(positionNumber, 0x01)

    ## Downloads the characteristics of template loaded in charbuffer 1
    characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')

    ## Hashes characteristics of template
    print('SHA-2 hash of template: ' + hashlib.sha256(characterics).hexdigest())

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)