pan wh
Published

Home Security

Using a Raspberry Pi with a motion sensor to detect movement and capture images of strangers.

BeginnerWork in progress878
Home Security

Things used in this project

Story

Read more

Code

main.html

HTML
html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="apple-touch-icon" sizes="76x76" href="static/assets/img/apple-icon.png">
  <link rel="icon" type="image/png" href="static/assets/img/favicon.png">
  <title>
    Home Automation
  </title>
  <!--     Fonts and icons     -->
  <link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,600,700,800" rel="stylesheet" />
  <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
  <!-- Nucleo Icons -->
  <link href="static/assets/css/nucleo-icons.css" rel="stylesheet" />
  <!-- CSS Files -->
  <link href="static/assets/css/black-dashboard.css?v=1.0.0" rel="stylesheet" />

  <style>
    .btnControlLED {
    display: inline-block;
    text-decoration: none;
    color: #FFF;
    width: 120px;
    height: 120px;
    line-height: 120px;
    border-radius: 50%;
    text-align: center;
    vertical-align: middle;
    overflow: hidden;
    background-image: -webkit-linear-gradient(45deg, #709dff 0%, #91fdb7 100%);    
    background-image: linear-gradient(45deg, #709dff 0%, #91fdb7 100%);
    transition: .4s;
  }

  .btnControlLED:hover{
    -webkit-transform: rotate(10deg);
    -ms-transform: rotate(10deg);
    transform: rotate(10deg);
  }

  .square_btn{
    display: inline-block;
    padding: 0.5em 1em;
    text-decoration: none;
    color: #67c5ff;
    border: dashed 1px #67c5ff;
    border-radius: 3px;
    transition: .4s;
  }

  .square_btn:hover {
      border-style: dotted;
      color: #679efd;
  }

  #LEDMessage {
    text-shadow: 2px 2px 4px #07f1ddb6;
    display: inline-block;
    padding: 0.5em 1em;
    text-decoration: none;
    border: double 4px #ec1c49;
    border-radius: 3px;
    transition: .4s;
  } 

  #LEDMessage:hover {
    background: #f2ff36;
  }
  </style>

  <!--Load Google Chart stuffs-->
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">

    // Load the Visualization API and the corechart package.
    google.charts.load('current', { 'packages': ['corechart'] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      setInterval(function () {
        getLightData('light');
      }, 3000);
    }

    function drawLightLineChart(data) {
      data = JSON.parse(data);
      lightgraphdata = new google.visualization.DataTable();
      lightgraphdata.addColumn('string', 'Time');
      lightgraphdata.addColumn('number', 'Light');

      for (var i = 0; i < 20; i++) {
        time = data[i].datetimeid
        light = data[i].value
        lightgraphdata.addRows([[time, light]]);
      }

      chart_opt = {
        curveType: 'function',
        vAxis: {
          minValue: 60,
          title: 'Light Value',
        }
      }

      lightChart = new google.visualization.LineChart(document.getElementById('chart'));
      lightChart.draw(lightgraphdata, chart_opt)
    }

    function getLightData(tableName) {
      jQuery.ajax({
        url: "/getData/" + tableName,
        type: 'POST',
        success: function (ndata, textStatus, xgr) {
          drawLightLineChart(ndata)
        }
      })
    }

    function getLEDStatus() {
      jQuery.ajax({
        url: "/ledStatus",
        type: 'POST',
        success: function (ndata, textStatus, xgr) {
          $("#LEDStatus").html(ndata.message)
        }
      })
    }

    function LEDswitch(action) {
      jQuery.ajax({
        url: "/switchLED/" + action,
        type: 'POST',
        success: function (ndata, textStatus, xgr) {
          $("#LEDMessage").html(ndata.message)
        }
      })
    }

    function captureImage(commandtext) {
      jQuery.ajax({
        url: "/captureImage",
        type: 'POST',
        data: { command: commandtext },
        success: function (ndata, textStatus, xgr) {
          $("#captureSuccess").html(ndata.message)
          var src = 'https://s3-us-west-2.amazonaws.com/iot-ay1819s2/home/1819s2_iot_BlackTea/' + ndata.message + ".jpg"
          $("img#imageCaptured").attr('src', src);
        }
      })
    }

    function recordVideo(commandtext) {
      jQuery.ajax({
        url: "/recordVideo",
        type: 'POST',
        data: { command: commandtext },
        success: function (ndata, textStatus, xgr) {
          $("#recordSuccess").html(ndata.message)
        }
      })
    }

  </script>
</head>

<body class="">
  <div class="wrapper">
    <div class="sidebar">
      <!--
        Tip 1: You can change the color of the sidebar using: data-color="blue | green | orange | red"
    -->
      <div class="sidebar-wrapper">
        <div class="logo">
          <a href="javascript:void(0)" class="simple-text logo-mini">

          </a>
          <a href="javascript:void(0)" class="simple-text logo-normal">
            HOME AUTOMATION
          </a>
        </div>
        <ul class="nav">
          <li>
            <a href="#">
              <i class="fas fa-thermometer-three-quarters"></i>
              <p>Light</p>
            </a>
          </li>
          <li>
            <a href="#">
              <i class="fas fa-camera-retro"></i>
              <p>Camera</p>
            </a>
          </li>
        </ul>
      </div>
    </div>
    <div class="main-panel">
      <!-- Navbar -->
      <nav class="navbar navbar-expand-lg navbar-absolute navbar-transparent">
        <div class="container-fluid">
          <div class="navbar-wrapper">
            <div class="navbar-toggle d-inline">
              <button type="button" class="navbar-toggler">
                <span class="navbar-toggler-bar bar1"></span>
                <span class="navbar-toggler-bar bar2"></span>
                <span class="navbar-toggler-bar bar3"></span>
              </button>
            </div>
            <a class="navbar-brand" href="javascript:void(0)">Dashboard</a>
          </div>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation" aria-expanded="false"
            aria-label="Toggle navigation">
            <span class="navbar-toggler-bar navbar-kebab"></span>
            <span class="navbar-toggler-bar navbar-kebab"></span>
            <span class="navbar-toggler-bar navbar-kebab"></span>
          </button>
          <div class="collapse navbar-collapse" id="navigation">
            <ul class="navbar-nav ml-auto">

              <li class="dropdown nav-item">
                <a href="#" class="dropdown-toggle nav-link" data-toggle="dropdown">
                  <div class="photo">
                    <img src="static/assets/img/anime3.png" alt="Profile Photo">
                  </div>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
      <div class="modal modal-search fade" id="searchModal" tabindex="-1" role="dialog" aria-labelledby="searchModal"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <input type="text" class="form-control" id="inlineFormInputGroup" placeholder="SEARCH">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <i class="tim-icons icon-simple-remove"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- End Navbar -->
      <div class="content">
        <div class="col-12">
          <h1 id="lightSection">Light</h1>
          <br>
        </div>

        <br>
        <br>
        <div class="row">
          <div class="col-4">

          </div>
          <div class="col-8">
            <h3>LED Control Button</h4>
              <br>
              <br>
          </div>
        </div>
        <br>

        <div class="row">
          <div class="col-3">
          </div>
          <div class="col-5">
            <a onclick="LEDswitch('on')" href="#" class="btnControlLED">ON</a>
          </div>
          <div class="col-4">
            <a onclick="LEDswitch('off')" href="#" class="btnControlLED">OFF</a>
          </div>
        </div>
        <br>
        <br>

        <div class="row">
          <div class="col-12">
            <div class="card card-chart">
              <div class="card-header ">
                <div class="row">
                  <div class="col-lg-12 text-left">
                    <h5 class="card-category">Light Data</h5>
                    <h2 class="card-title">Light Records</h2>
                  </div>
                </div>
              </div>
              <div class="card-body">
                <div id="chart" stlye="height=480px">
                </div>
              </div>
            </div>
          </div>
        </div>
        <br>
        <br>

        <div class="row">
          <div class="col-12">
            <button type="button" class="btn btn-primary" id='captureImage' onclick="captureImage('captureImage')">Capture
              Image</button>
            <a id='captureSuccess'></a>
            <!-- Image should be displayed (bucket must have public read access) -->
            <img id="imageCaptured" src="">
            <button type="button" class="btn btn-primary" id='recordVideo' onclick="recordVideo('record')">Record Video</button>
            <a id='recordSuccess'></a>
            <br>

          </div>
        </div>

      </div>
      <footer class="footer">
        <div class="container-fluid">

          <div class="copyright">
            ©
            <script>
              document.write(new Date().getFullYear())
            </script> created by
            <a href="javascript:void(0)" target="_blank">WeiChen</a>
          </div>
        </div>
      </footer>
    </div>
  </div>
  <div class="fixed-plugin">
    <div class="dropdown show-dropdown">
      <a href="#" data-toggle="dropdown">
        <i class="fa fa-cog fa-2x"> </i>
      </a>
      <ul class="dropdown-menu">
        <li class="header-title"> Sidebar Background</li>
        <li class="adjustments-line">
          <a href="javascript:void(0)" class="switch-trigger background-color">
            <div class="badge-colors text-center">
              <span class="badge filter badge-primary active" data-color="primary"></span>
              <span class="badge filter badge-info" data-color="blue"></span>
              <span class="badge filter badge-success" data-color="green"></span>
            </div>
            <div class="clearfix"></div>
          </a>
        </li>
        <li class="adjustments-line text-center color-change">
          <span class="color-label">LIGHT MODE</span>
          <span class="badge light-badge mr-2"></span>
          <span class="badge dark-badge ml-2"></span>
          <span class="color-label">DARK MODE</span>
        </li>
        <br>
        <br>
      </ul>
    </div>
  </div>
  <!--   Core JS Files   -->
  <script src="static/assets/js/core/jquery.min.js"></script>
  <script src="static/assets/js/core/popper.min.js"></script>
  <script src="static/assets/js/core/bootstrap.min.js"></script>
  <script src="static/assets/js/plugins/perfect-scrollbar.jquery.min.js"></script>
  <!--  Google Maps Plugin    -->
  <!-- Place this tag in your head or just before your close body tag. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>
  <!-- Chart JS -->
  <script src="static/assets/js/plugins/chartjs.min.js"></script>
  <!--  Notifications Plugin    -->
  <script src="static/assets/js/plugins/bootstrap-notify.js"></script>
  <!-- Control Center for Black Dashboard: parallax effects, scripts for the example pages etc -->
  <script src="static/assets/js/black-dashboard.min.js?v=1.0.0"></script>
  <script>
    $(document).ready(function () {
      $().ready(function () {
        $sidebar = $('.sidebar');
        $navbar = $('.navbar');
        $main_panel = $('.main-panel');

        $full_page = $('.full-page');

        $sidebar_responsive = $('body > .navbar-collapse');
        sidebar_mini_active = true;
        white_color = false;

        window_width = $(window).width();

        fixed_plugin_open = $('.sidebar .sidebar-wrapper .nav li.active a p').html();

        $('.fixed-plugin a').click(function (event) {
          if ($(this).hasClass('switch-trigger')) {
            if (event.stopPropagation) {
              event.stopPropagation();
            } else if (window.event) {
              window.event.cancelBubble = true;
            }
          }
        });

        $('.fixed-plugin .background-color span').click(function () {
          $(this).siblings().removeClass('active');
          $(this).addClass('active');

          var new_color = $(this).data('color');

          if ($sidebar.length != 0) {
            $sidebar.attr('data', new_color);
          }

          if ($main_panel.length != 0) {
            $main_panel.attr('data', new_color);
          }

          if ($full_page.length != 0) {
            $full_page.attr('filter-color', new_color);
          }

          if ($sidebar_responsive.length != 0) {
            $sidebar_responsive.attr('data', new_color);
          }
        });

        $('.switch-sidebar-mini input').on("switchChange.bootstrapSwitch", function () {
          var $btn = $(this);

          if (sidebar_mini_active == true) {
            $('body').removeClass('sidebar-mini');
            sidebar_mini_active = false;
            blackDashboard.showSidebarMessage('Sidebar mini deactivated...');
          } else {
            $('body').addClass('sidebar-mini');
            sidebar_mini_active = true;
            blackDashboard.showSidebarMessage('Sidebar mini activated...');
          }

          // we simulate the window Resize so the charts will get updated in realtime.
          var simulateWindowResize = setInterval(function () {
            window.dispatchEvent(new Event('resize'));
          }, 180);

          // we stop the simulation of Window Resize after the animations are completed
          setTimeout(function () {
            clearInterval(simulateWindowResize);
          }, 1000);
        });

        $('.switch-change-color input').on("switchChange.bootstrapSwitch", function () {
          var $btn = $(this);

          if (white_color == true) {

            $('body').addClass('change-background');
            setTimeout(function () {
              $('body').removeClass('change-background');
              $('body').removeClass('white-content');
            }, 900);
            white_color = false;
          } else {

            $('body').addClass('change-background');
            setTimeout(function () {
              $('body').removeClass('change-background');
              $('body').addClass('white-content');
            }, 900);

            white_color = true;
          }
        });

        $('.light-badge').click(function () {
          $('body').addClass('white-content');
        });

        $('.dark-badge').click(function () {
          $('body').removeClass('white-content');
        });
      });
    });
  </script>
  <script>
    $(document).ready(function () {
      // Javascript method's body can be found in assets/js/demos.js
      demo.initDashboardPageCharts();
    });
  </script>
</body>

</html>

server.py

Python
import sys
import Adafruit_DHT
import mysql.connector
from flask import Flask,render_template,request,jsonify, Response
from gpiozero import LED, MCP3008, MotionSensor
from time import sleep
from flask_basicauth import BasicAuth
import json
import datetime
import decimal
import boto3
import botocore
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from picamera import PiCamera

# Motion Sensor
pir = MotionSensor(26, sample_rate=5,queue_len=1)

# LED
led = LED(18)

# LDR
adc = MCP3008(channel=0)

# Uploads the given file using a managed uploader, which will split up large
# files automatically and upload parts in parallel.
BUCKET = 'iot-ay1819s2'  # **DO NOT** CHANGE THIS
location = {'LocationConstraint': 'us-west-2'}  # **DO NOT** CHANGE THIS
file_path = "/home/pi/CA2"  # CHANGE THIS to point to the path of your file

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

host = "abpl27ba00qyj-ats.iot.us-west-2.amazonaws.com"
rootCAPath = "rootca.pem"
certificatePath = "936bac045c-certificate.pem.crt"
privateKeyPath = "936bac045c-private.pem.key"

my_rpi = AWSIoTMQTTClient("p1612596")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
my_rpi.connect()

def uploadToS3(file_path, file_name, bucket_name, location):
    s3 = boto3.resource('s3')  # Create an S3 resource
    exists = True

    try:
        s3.meta.client.head_bucket(Bucket=bucket_name)
    except botocore.exceptions.ClientError as e:
        error_code = int(e.response['Error']['Code'])
        if error_code == 404:
            exists = False

    if exists == False:
        s3.create_bucket(Bucket=bucket_name,
                         CreateBucketConfiguration=location)

    # Upload the file
    full_path = file_path + "/" + file_name
    # full_path = file_path
    s3.Object(bucket_name, file_name).put(Body=open(full_path, 'rb'))
    print("File uploaded")

# Flask project name 
app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = 'pi'
app.config['BASIC_AUTH_PASSWORD'] = 'pi'
app.config['BASIC_AUTH_FORCE'] = True

basic_auth = BasicAuth(app)

@app.route("/")
@basic_auth.required
def main():
   return render_template("main.html")

def ledCallback(client, userdata, message):
    print("Received a new message: ")
    print(message.payload)
    print("from topic: ")
    print(message.topic)
    ("--------------\n\n")
    print(message.payload[12:14])
    action = message.payload[12:14]
    if action == 'on':
          led.on()
    else:
          led.off()
my_rpi.subscribe("btsensors/led", 1,ledCallback)

@app.route("/getData/<tableName>",methods=['POST','GET'])
def getData(tableName):
   try:
      #connect to dynamodb
      dynamodb = boto3.resource('dynamodb',
      aws_access_key_id = 'AKIAJQN4S5EWMQZKXB7Q',
      aws_secret_access_key = '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',
      region_name = 'us-west-2'
      )
      #table name in db
      table = dynamodb.Table('BlackTea_light')  
      #get the data from db
      data = table.scan()
      #retrieve all items
      data = data['Items']
      # to fix decimal issue in the DynamoDB data format
      data2 = json.dumps(data, indent=4, cls=DecimalEncoder)
      return jsonify(data2)        
   except:
            print("Error")
            print(sys.exc_info()[0])
            print(sys.exc_info()[1])

@app.route("/switchLED/<action>",methods=['POST'])
def switchLED(action):
    try:
        if action == 'on':
           message = {}
           message["deviceid"] = "BlackTea"
           import datetime as datetime
           now = datetime.datetime.now()
           message["datetimeid"] = now.isoformat()      
           message["action"] = 'on'
           import json
           my_rpi.publish("btsensors/led", json.dumps(message), 1)
        else:
           message = {}
           message["deviceid"] = "BlackTea"
           import datetime as datetime
           now = datetime.datetime.now()
           message["datetimeid"] = now.isoformat()      
           message["action"] = 'off'
           import json
           my_rpi.publish("btsensors/led", json.dumps(message), 1)
    except:
        message = "Error while trying to control LED"
        print(sys.exc_info()[0])
        print(sys.exc_info()[1])
    data = {"message": message}
    return jsonify(data)

@app.route("/captureImage",methods=['POST','GET'])
def captureImage():
    try:
        command = request.form["command"]
        if command == "captureImage":
            with PiCamera() as camera:
                file_name = "home/1819s2_iot_BlackTea/" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ".jpg"   # **DO NOT** CHANGE THIS
                camera.capture(file_name)
                uploadToS3(file_path, file_name, BUCKET, location)
                message = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    except:
        message = "Error while trying to capture image"
        print(sys.exc_info()[0])
        print(sys.exc_info()[1])
    
    data = {"message": message}
    
    return jsonify(data)  

@app.route("/recordVideo",methods=['POST','GET'])
def recordVideo():
    try:
        command = request.form["command"]
        if command == "record":
            with PiCamera() as camera:
                camera.resolution = (640, 480)
                file_name = "home/1819s2_iot_BlackTea/" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ".h264"   # **DO NOT** CHANGE THIS
                camera.start_recording(file_name)
                camera.wait_recording(10)
                camera.stop_recording()
                uploadToS3(file_path, file_name, BUCKET, location)
                message = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    except:
        message = "Error while trying to recording video"
        print(sys.exc_info()[0])
        print(sys.exc_info()[1])
    
    data = {"message": message}
    
    return jsonify(data)

if __name__ == '__main__':
   app.run(host="0.0.0.0", debug=False)

imageDetect.py

Python
import boto3
import botocore
from picamera import PiCamera
from time import sleep
import datetime
from gpiozero import MotionSensor
from time import time
from twilio.rest import Client
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.mime.base import MIMEBase
from email import encoders
import os.path

# twilio msg api
account_sid = 'AC2940ed8293bfb28fc196c94f67fec806' 
auth_token = 'a17d9f85dc46f9e45737306f644e1638' 
client = Client(account_sid, auth_token) 

my_hp = "+6587532120"
twilio_hp = "+14152374364"

# motion sensor
pir = MotionSensor(26, sample_rate=5, queue_len=1)

# Set the filename and bucket name
username = "1819s2_iot_BlackTea"  # CHANGE THIS to AWS login acct
BUCKET = 'iot-ay1819s2'  # **DO NOT** CHANGE THIS
location = {'LocationConstraint': 'us-west-2'}  # **DO NOT** CHANGE THIS
file_path = "/home/pi/CA2"  # CHANGE THIS to point to the path of your file
file_name = "home/" + username + "/" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ".jpg"   # **DO NOT** CHANGE THIS
KEY = "home/1819s2_iot_BlackTea/" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ".jpg"
COLLECTION = "MyCollection"

# Email you want to send the update from (only works with gmail)
fromEmail = 'chenxxxxxl0731@gmail.com'
fromEmailPassword = '68754563'

# Email you want to send the update to
toEmail = 'linweichen0731@hotmail.com'

file_location = '/home/pi/CA2/home/1819s2_iot_BlackTea/'+ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +'.jpg'

def twilioMsg():
   sms = "Caution ! There is a stranger outside your doorstep, checkout your email for image"
   message = client.messages.create(to=my_hp,
                                             from_=twilio_hp,
                                             body=sms) 

def takePhoto(file_path, file_name):
    with PiCamera() as camera:
        full_path = file_path + "/" + file_name
        camera.capture(full_path)
        sleep(5)

def uploadToS3(file_path, file_name, bucket_name, location):
    s3 = boto3.resource('s3')  # Create an S3 resource
    exists = True

    try:
        s3.meta.client.head_bucket(Bucket=bucket_name)
    except botocore.exceptions.ClientError as e:
        error_code = int(e.response['Error']['Code'])
        if error_code == 404:
            exists = False

    if exists == False:
        s3.create_bucket(Bucket=bucket_name,
                         CreateBucketConfiguration=location)

    # Upload the file
    full_path = file_path + "/" + file_name
    # full_path = file_path
    s3.Object(bucket_name, file_name).put(Body=open(full_path, 'rb'))
    print("File uploaded")


def search_faces_by_image(bucket, key, collection_id, threshold=0, region="us-west-2"):
	rekognition = boto3.client("rekognition", region)
	response = rekognition.search_faces_by_image(
		Image={
			"S3Object": {
				"Bucket": bucket,
				"Name": key,
			}
		},
		CollectionId=collection_id,
		FaceMatchThreshold=threshold,
	)
	return response['FaceMatches']

def sendEmail():
    subject = 'Visitor/Intruder'
    message = ''

    msg = MIMEMultipart()
    msg['From'] = fromEmail
    msg['To'] = toEmail
    msg['Subject'] = subject

    msg.attach(MIMEText(message, 'plain'))

    filename = os.path.basename(file_location)
    attachment = open(file_location, "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    msg.attach(part)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromEmail, fromEmailPassword)
    text = msg.as_string()
    server.sendmail(fromEmail, toEmail, text)
    server.quit()

while True:
    takePhoto(file_path, file_name)
    uploadToS3(file_path, file_name, BUCKET, location)
    for record in search_faces_by_image(BUCKET, KEY, COLLECTION):
        face = record['Face']
        print("Matched Face ({}%)".format(record['Similarity']))
        print("  FaceId : {}".format(face['FaceId']))
        print("  ImageId : {}".format(face['ExternalImageId']))
        if (record['Similarity'] < 80):
            print("Stranger")
            twilioMsg()
    sendEmail()
    sleep(60)

Credits

pan wh

pan wh

1 project • 0 followers

Comments

Add projectSign up / Login