Von Christopher Almendral
Published © GPL3+

HomeSecure

An anti-theft system used to prevent or deter unauthorized appropriation of items considered valuable.

AdvancedFull instructions provided5 hours1,501
HomeSecure

Things used in this project

Hardware components

Raspberry Pi 3 Model B
Raspberry Pi 3 Model B
×1
Buzzer
Buzzer
×1
DHT11 Temperature & Humidity Sensor (4 pins)
DHT11 Temperature & Humidity Sensor (4 pins)
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
Breadboard (generic)
Breadboard (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Resistor 220 ohm
Resistor 220 ohm
×1
Camera Module
Raspberry Pi Camera Module
×1

Software apps and online services

AWS RDS
Amazon Web Services AWS RDS
AWS S3
Amazon Web Services AWS S3
AWS EC2
Amazon Web Services AWS EC2
Telegram
Messaging service
Flask
Used to create the website.
AWS IoT
Amazon Web Services AWS IoT

Story

Read more

Schematics

Documentation

More detailed instructions on how to setup the project.

Homesecure database

SQL file for the database tables

Code

index.html

HTML
The first html file index.html is a HTML file. There are three different sub pages on the index pages representing different room that the three different raspberry pi are placed in. Each on the pages receive information such as the temperature data that is stored on the database, which refreshes every 5 seconds. It also contain the real-life state of the buzzer, and user is also able to control the buzzer. Users can also view the photo taken throught motion detection and photo taken through the telegram commands
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
    <title>Home Secure</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class="container-fluid'">
    <div class="row">
        <nav class="col-md-2 d-none d-md-block bg-light sidebar">
            <div class="sidebar-sticky">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link active" href="/">
                            <span data-feather="home"></span>
                            Rooms <span class="sr-only">(current)</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link  " href="/settings">
                            <span data-feather="video"></span>
                            Settings
                        </a>
                    </li>
                </ul>
            </div>
        </nav>
    </div>
    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <h1 class="h2">Components</h1>
        </div>

        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="entrance-tab" data-toggle="tab" href="#entrance" role="tab"
                   aria-controls="entrance"
                   aria-selected="true">Entrance</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="living-room-tab" data-toggle="tab" href="#living-room" role="tab"
                   aria-controls="living-room" aria-selected="false">Living Room</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="master-bedroom-tab" data-toggle="tab" href="#master-bedroom" role="tab"
                   aria-controls="master-bedroom" aria-selected="false">Master Bedroom</a>
            </li>
        </ul>
        <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="entrance" role="tabpanel" aria-labelledby="entrance-tab">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h4">Actuators</h1>
                </div>
                <div class="container">
                        <div id="canvas-wrapper-1">

                             <canvas class="my-4 w-100" id="myChart1" width="900" height="380"></canvas>
                        </div>
                    <div class="row">
                        <div class="col-md-12 text-center">
                            {% if buzzerStatus1 %}
                            <image height="163px" id="image-buzzer1"
                                   src="{{ url_for('static',filename='img/buzzer_on.png') }}"></image>
                            <a class="btn btn-danger"   href="/buzzer/1/off">TURN OFF</a>
                            {% else %}
                            <image height="163px" id="image-buzzer1"
                                   src="{{ url_for('static',filename='img/buzzer_off.png') }}"></image>
                            <a class="btn btn-success"href="/buzzer/1/on">TURN ON</a>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h3">Picture by motion</h1>
                </div>
                <div class="container">
                    <div class="row">
                        {% for imageMotion in imageMotion1 %}
                        <div class="col-md-4">
                            <div class="card mb-4 box-shadow">
                                <img class="card-img-top" src="{{imageMotion}}"/>
                                <!--<div class="card-body">-->
                                    <!--Date captured:-->
                                <!--</div>-->
                            </div>
                        </div>
                        {% endfor %}

                    </div>
                </div>
                 <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h3">Picture by telegram</h1>
                </div>
                <div class="container">
                    <div class="row">
                        {% for imageTelegram in imageTelegram1 %}
                        <div class="col-md-4">
                            <div class="card mb-4 box-shadow">
                                <img class="card-img-top" src="{{imageTelegram}}"/>
                                <!--<div class="card-body">-->
                                    <!--Date captured:-->
                                <!--</div>-->
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="living-room" role="tabpanel" aria-labelledby="living-room-tab">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h4">Actuators</h1>
                </div>
                <div class="container">
                    <div id="canvas-wrapper-2">
                        <canvas class="my-4 w-100" id="myChart2" width="900" height="380"></canvas>
                    </div>

                    <div class="row">
                        <div class="col-md-12 text-center">
                            {% if buzzerStatus2 %}
                            <image height="163px" id="image-buzzer1"
                                   src="{{ url_for('static',filename='img/buzzer_on.png') }}"></image>
                            <a class="btn btn-danger"   href="/buzzer/2/off">TURN OFF</a>
                            {% else %}
                            <image height="163px" id="image-buzzer1"
                                   src="{{ url_for('static',filename='img/buzzer_off.png') }}"></image>
                            <a class="btn btn-success"href="/buzzer/2/on">TURN ON</a>
                            {% endif %}
                        </div>
                    </div>
                </div>


                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h3">Picture by motion</h1>
                </div>
                <div class="container">
                    <div class="row">
                        {% for imageMotion in imageMotion2 %}
                        <div class="col-md-4">
                            <div class="card mb-4 box-shadow">
                                <img class="card-img-top" src="{{imageMotion}}"/>
                                <!--<div class="card-body">-->
                                    <!--Date captured:-->
                                <!--</div>-->
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                 <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h3">Picture by telegram</h1>
                </div>
                <div class="container">
                    <div class="row">
                        {% for imageTelegram in imageTelegram2 %}
                        <div class="col-md-4">
                            <div class="card mb-4 box-shadow">
                                <img class="card-img-top" src="{{imageTelegram}}"/>
                                <!--<div class="card-body">-->
                                    <!--Date captured:-->
                                <!--</div>-->
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="master-bedroom" role="tabpanel" aria-labelledby="master-bedroom-tab">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h4">Actuators</h1>
                </div>
                <div class="container">
                    <div id="canvas-wrapper-3">
                        <canvas class="my-4 w-100" id="myChart3" width="900" height="380"></canvas>
                    </div>

                    <div class="row">
                        <div class="col-md-12 text-center">
                            {% if buzzerStatus3 %}
                            <image height="163px" id="image-buzzer1"
                                   src="{{ url_for('static',filename='img/buzzer_on.png') }}"></image>
                            <a class="btn btn-danger"   href="/buzzer/3/off">TURN OFF</a>
                            {% else %}
                            <image height="163px" id="image-buzzer1"
                                   src="{{ url_for('static',filename='img/buzzer_off.png') }}"></image>
                            <a class="btn btn-success"href="/buzzer/3/on">TURN ON</a>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h3">Picture by motion</h1>
                </div>
                <div class="container">
                    <div class="row">
                        {% for imageMotion in imageMotion3 %}
                        <div class="col-md-4">
                            <div class="card mb-4 box-shadow">
                                <img class="card-img-top" src="{{imageMotion}}"/>
                                <!--<div class="card-body">-->
                                    <!--Date captured:-->
                                <!--</div>-->
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>

                 <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h3">Picture by telegram</h1>
                </div>
                <div class="container">
                    <div class="row">
                        {% for imageTelegram in imageTelegram3 %}
                        <div class="col-md-4">
                            <div class="card mb-4 box-shadow">
                                <img class="card-img-top" src="{{imageTelegram}}"/>
                                <!--<div class="card-body">-->
                                    <!--Date captured:-->
                                <!--</div>-->
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>


<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://unpkg.com/feather-icons/dist/feather.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script>
  var led = false;
  var buzzer = false;

    var ctx1 = document.getElementById("myChart1");
    var myChart1;
    var ctx2 = document.getElementById("myChart2");
    var myChart2;
    var ctx3 = document.getElementById("myChart3");
    var myChart3;
    var refresh1 = null;
    var refresh2 = null;
    var refresh3 = null;
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
      var target = $(e.target).attr("href") // activated tab
      if(target == "#entrance")
      {
        refresh1 =  setInterval(function(){
            updateChart1();
        },5000);

        if(refresh2)
        {
            clearInterval(refresh2)
        }

        if(refresh3)
        {
            clearInterval(refresh3)
        }
      }
      else if(target == "#living-room")
      {
        refresh2 =  setInterval(function(){
            updateChart2();
        },5000);

        if(refresh1)
        {
            clearInterval(refresh1)
        }

        if(refresh3)
        {
            clearInterval(refresh3)
        }
      }
      else if(target == "#master-bedroom")
      {
        refresh3 =  setInterval(function(){
            updateChart3();
        },5000);

        if(refresh2)
        {
            clearInterval(refresh2)
        }

        if(refresh1)
        {
            clearInterval(refresh1)
        }
      }
    });
    myChart1 = new Chart(ctx1, {
        type: 'line',
        data: {
          labels: {{ dateTimeList1|safe}},
          datasets: [{
            data: {{ tempList1|safe}},
            lineTension: 0,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'
          }]
        },showTooltips: true,
        options: {
          spanGaps: true,
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: false
              }
            }]
          },
          legend: {
            display: false,
          }
	}
      });
	<!--getData1.done(function(results){-->
        <!--myChart1 = new Chart(ctx1, {-->
        <!--type: 'line',-->
        <!--data: {-->
          <!--labels: results.dateTime,-->
          <!--datasets: [{-->
            <!--data: results.temperature,-->
            <!--lineTension: 0,-->
            <!--backgroundColor: 'transparent',-->
            <!--borderColor: '#007bff',-->
            <!--borderWidth: 4,-->
            <!--pointBackgroundColor: '#007bff'-->
          <!--}]-->
        <!--},showTooltips: true,-->
        <!--options: {-->
             <!--spanGaps: true,-->
	<!--},-->
          <!--legend: {-->
            <!--display: false,-->
          <!--}-->
        <!--}-->
      <!--);-->
    <!--});-->

    function updateChart1() {
        ('#myChart1').remove();
        $('#canvas-wrapper-1').append('<canvas class="my-4 w-100" id="myChart1" width="900" height="380"></canvas>');
        var updatedData = jQuery.get('/readTemperature/1');
        ctx1 = document.getElementById("myChart1");
        updatedData.done(function(results){
       myChart1 = new Chart(ctx1, {
        type: 'line',
        data: {
          labels: results.dateTime,
          datasets: [{
            data: results.temperature,
            lineTension: 0,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'
          }]
        },showTooltips: true,
        options: {
	  spanGaps: true,
          animation: {
            duration:0,

          },
          hover:{
            animationDuration:0,
          },
          legend: {
            display: false,
          }
        }
	   });
		});
	}

    myChart2 = new Chart(ctx2, {
        type: 'line',
        data: {
          labels: {{ dateTimeList2|safe}},
          datasets: [{
            data: {{ tempList2|safe}},
            lineTension: 0,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'
          }]
        },showTooltips: true,
        options: {
          spanGaps: true,
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: false
              }
            }]
          },
          legend: {
            display: false,
          }
	}
      });
	<!--getData2.done(function(results){-->
        <!--myChart2 = new Chart(ctx2, {-->
        <!--type: 'line',-->
        <!--data: {-->
          <!--labels: results.dateTime,-->
          <!--datasets: [{-->
            <!--data: results.temperature,-->
            <!--lineTension: 0,-->
            <!--backgroundColor: 'transparent',-->
            <!--borderColor: '#007bff',-->
            <!--borderWidth: 4,-->
            <!--pointBackgroundColor: '#007bff'-->
          <!--}]-->
        <!--},showTooltips: true,-->
        <!--options: {-->
             <!--spanGaps: true,-->
	<!--},-->
          <!--legend: {-->
            <!--display: false,-->
          <!--}-->
        <!--}-->
      <!--);-->
    <!--});-->

    function updateChart2() {
        $('#myChart2').remove();
        $('#canvas-wrapper-2').append('<canvas class="my-4 w-100" id="myChart2" width="900" height="380"></canvas>');
        var updatedData = jQuery.get('/readTemperature/2');
        ctx2 = document.getElementById("myChart2");
        updatedData.done(function(results){
            myChart2 = new Chart(ctx2, {
        type: 'line',
        data: {
          labels: results.dateTime,
          datasets: [{
            data: results.temperature,
            lineTension: 0,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'
          }]
        },showTooltips: true,
        options: {
	  spanGaps: true,
          animation: {
            duration:0,

          },
          hover:{
            animationDuration:0,
          },
          legend: {
            display: false,
          }
        }
	   });
		});
	}

	myChart3 = new Chart(ctx3, {
        type: 'line',
        data: {
          labels: {{ dateTimeList3|safe}},
          datasets: [{
            data: {{ tempList3|safe}},
            lineTension: 0,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'
          }]
        },showTooltips: true,
        options: {
          spanGaps: true,
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: false
              }
            }]
          },
          legend: {
            display: false,
          }
	}
      });
	<!--getData3.done(function(results){-->
        <!--myChart3 = new Chart(ctx3, {-->
        <!--type: 'line',-->
        <!--data: {-->
          <!--labels: results.dateTime,-->
          <!--datasets: [{-->
            <!--data: results.temperature,-->
            <!--lineTension: 0,-->
            <!--backgroundColor: 'transparent',-->
            <!--borderColor: '#007bff',-->
            <!--borderWidth: 4,-->
            <!--pointBackgroundColor: '#007bff'-->
          <!--}]-->
        <!--},showTooltips: true,-->
        <!--options: {-->
             <!--spanGaps: true,-->
	<!--},-->
          <!--legend: {-->
            <!--display: false,-->
          <!--}-->
        <!--}-->
      <!--);-->
    <!--});-->

    function updateChart3() {
        ('#myChart3').remove();
        $('#canvas-wrapper-3').append('<canvas class="my-4 w-100" id="myChart3" width="900" height="380"></canvas>');
        var updatedData = jQuery.get('/readTemperature/3');
        ctx3 = document.getElementById("myChart3");
        updatedData.done(function(results){
       myChart3 = new Chart(ctx3, {
        type: 'line',
        data: {
          labels: results.dateTime,
          datasets: [{
            data: results.temperature,
            lineTension: 0,
            backgroundColor: 'transparent',
            borderColor: '#007bff',
            borderWidth: 4,
            pointBackgroundColor: '#007bff'
          }]
        },showTooltips: true,
        options: {
	  spanGaps: true,
          animation: {
            duration:0,

          },
          hover:{
            animationDuration:0,
          },
          legend: {
            display: false,
          }
        }
	   });
		});
	}
    <!--setInterval(function(){-->
        <!--updateChart1();-->
        <!--console.log('Updating');-->
    <!--},5000);-->

    <!--setInterval(function(){-->
        <!--updateChart2();-->
        <!--console.log('Updating');-->
    <!--},10000);-->

    <!--setInterval(function(){-->
        <!--updateChart3();-->
        <!--console.log('Updating');-->
    <!--},15000);-->


    function validateForm() {
        var onBuzzer = document.forms["telegramForm"]["onBuzzer"].value;
        var offBuzzer = document.forms["telegramForm"]["offBuzzer"].value;
        var takePhoto = document.forms["telegramForm"]["takePhoto"].value;
        var getTemp = document.forms["telegramForm"]["getTemp"].value;
        var getHumidity = document.forms["telegramForm"]["getHumidity"].value;
        var tempLimit = document.forms["telegramForm"]["tempLimit"].value;
        if (onBuzzer == "" || offBuzzer == "" || takePhoto == "" || getTemp == "" || getHumidity == "") {
            alert("No commmand can be left empty!");
            return false;
        }
        else if (tempLimit == "") {
            alert("Temperature limit cannot be empty!");
            return false;
        }
        else if (isNaN(tempLimit)) {
            alert("Temperature limit must be in numbers only!");
            return false;
        }
      }




</script>
</body>
</html>

settings.html

HTML
The second html file settings.html has also three sub pages for the different raspberry pi. The settings pages is for the users to edit the telegram commands and switch on and off for the motion detection
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
    <title>Home Secure</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class="container-fluid'">
    <div class="row">
        <nav class="col-md-2 d-none d-md-block bg-light sidebar">
            <div class="sidebar-sticky">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link " href="/">
                            <span data-feather="home"></span>
                            Rooms <span class="sr-only">(current)</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active " href="/settings">
                            <span data-feather="video"></span>
                            Settings
                        </a>
                    </li>
                </ul>
            </div>
        </nav>
    </div>
    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">

        {% include 'includes/_message.html' %}
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <h1 class="h2">Settings</h1>
        </div>
        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="entrance-tab" data-toggle="tab" href="#entrance" role="tab"
                   aria-controls="entrance"
                   aria-selected="true">Entrance</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="living-room-tab" data-toggle="tab" href="#living-room" role="tab"
                   aria-controls="living-room" aria-selected="false">Living Room</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="master-bedroom-tab" data-toggle="tab" href="#master-bedroom" role="tab"
                   aria-controls="master-bedroom" aria-selected="false">Master Bedroom</a>
            </li>
        </ul>
        <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="entrance" role="tabpanel" aria-labelledby="entrance-tab">
                <form name="telegramForm" method="POST" onsubmit="return validateForm()">
                    <input type="hidden" name="settingId" value="{{settingId1}}"/>
                    <br>
                    On buzzer command:<br>
                    <input name="onBuzzerRoom" class="form-control" type="text" value="{{onBuzzerRoom1}}" required><br>
                    Off buzzer command:<br>
                    <input name="offBuzzerRoom" class="form-control" type="text" value="{{offBuzzerRoom1}}"
                           required><br>
                    Take a photo command:<br>
                    <input name="takePhotoRoom" class="form-control" type="text" value="{{takePhotoCommandRoom1}}"
                           required><br>
                    Get temperature value command:<br>
                    <input name="getTempRoom" class="form-control" type="text" value="{{getTempCommandRoom1}}" required><br>
                    Get Humidity value command:<br>
                    <input name="getHumidityRoom" class="form-control" type="text" value="{{getHumidityCommandRoom1}}"
                           required><br>
                    {% if motionDetectionRoom1 %}
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="1" checked>On
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="0">Off
                    </label>
                    {% else %}
                     <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="1" >On
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="0" checked>Off
                    </label>

                    {% endif %}
                    <p><input type="submit" class="btn btn-primary" value="Save"></p>

                </form>
            </div>
            <div class="tab-pane fade" id="living-room" role="tabpanel" aria-labelledby="living-room-tab">
                <br>
                <form name="telegramForm" method="POST" onsubmit="return validateForm()">
                    <input type="hidden" name="settingId" value="{{settingId2}}"/>
                    On buzzer command:<br>
                    <input name="onBuzzerRoom" class="form-control" type="text" value="{{onBuzzerRoom2}}" required><br>
                    Off buzzer command:<br>
                    <input name="offBuzzerRoom" class="form-control" type="text" value="{{offBuzzerRoom2}}"
                           required><br>
                    Take a photo command:<br>
                    <input name="takePhotoRoom" class="form-control" type="text" value="{{takePhotoCommandRoom2}}"
                           required><br>
                    Get temperature value command:<br>
                    <input name="getTempRoom" class="form-control" type="text" value="{{getTempCommandRoom2}}" required><br>
                    Get Humidity value command:<br>
                    <input name="getHumidityRoom" class="form-control" type="text"
                           value="{{getHumidityCommandRoom2}}" required><br>

                    {% if motionDetection2 %}
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="1" checked>On
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="0">Off
                    </label>
                    {% else %}
                     <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="1" >On
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="0" checked>Off
                    </label>

                    {% endif %}
                    <p><input type="submit" class="btn btn-primary" value="Save"></p>
                </form>
            </div>

            <div class="tab-pane fade" id="master-bedroom" role="tabpanel" aria-labelledby="master-bedroom-tab">
                <br>
                <form name="telegramForm" method="POST" onsubmit="return validateForm()">
                    <input type="hidden" name="settingId" value="{{settingId3}}"/>
                    On buzzer command:<br>
                    <input name="onBuzzerRoom" class="form-control" type="text" value="{{onBuzzerRoom3}}" required><br>
                    Off buzzer command:<br>
                    <input name="offBuzzerRoom" class="form-control" type="text" value="{{offBuzzerRoom3}}"
                           required><br>
                    Take a photo command:<br>
                    <input name="takePhotoRoom" class="form-control" type="text" value="{{takePhotoCommandRoom3}}"
                           required><br>
                    Get temperature value command:<br>
                    <input name="getTempRoom" class="form-control" type="text" value="{{getTempCommandRoom3}}" required><br>
                    Get Humidity value command:<br>
                    <input name="getHumidityRoom" class="form-control" type="text"
                           value="{{getHumidityCommandRoom3}}" required><br>
                    {% if motionDetectionRoom3 %}
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="1" checked>On
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="0">Off
                    </label>
                    {% else %}
                     <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="1" >On
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="motionDetectionRoom" value="0" checked>Off
                    </label>

                    {% endif %}
                    <br>
                    <p><input type="submit" class="btn btn-primary" value="Save"></p>
                </form>
            </div>
        </div>

        <div class="container">

        </div>
    </main>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://unpkg.com/feather-icons/dist/feather.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script>
  var led = false;
  var buzzer = false;


    function validateForm() {
        var onBuzzer = document.forms["telegramForm"]["onBuzzer"].value;
        var offBuzzer = document.forms["telegramForm"]["offBuzzer"].value;
        var takePhoto = document.forms["telegramForm"]["takePhoto"].value;
        var getTemp = document.forms["telegramForm"]["getTemp"].value;
        var getHumidity = document.forms["telegramForm"]["getHumidity"].value;
        var tempLimit = document.forms["telegramForm"]["tempLimit"].value;
        if (onBuzzer == "" || offBuzzer == "" || takePhoto == "" || getTemp == "" || getHumidity == "") {
            alert("No commmand can be left empty!");
            return false;
        }
        else if (tempLimit == "") {
            alert("Temperature limit cannot be empty!");
            return false;
        }
        else if (isNaN(tempLimit)) {
            alert("Temperature limit must be in numbers only!");
            return false;
        }
      }




</script>
</body>
</html>

_navbar.html

HTML
There’s another folder called includes with is inside of the templates folders. Which contains the html code for the _navbar.html, which is displayed on every html file.
<nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
      <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Home Secure</a>
      <!--<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">-->
      <ul class="navbar-nav px-3">
        <li class="nav-item text-nowrap">
          <!--<a class="nav-link" href="#">Sign out</a>-->
        </li>
      </ul>
</nav>

_message.html

HTML
_message.html is the message which is shown when user save changes to the settings page.
{% with messages = get_flashed_messages(with_categories=true) %}
    <br>
<br>
<br><br>
  {% if messages %}
    {% for category, message in messages %}
      <div class="alert alert-{{ category }}">{{ message }}</div>
    {% endfor %}
  {% endif %}
{% endwith %}

rasppi.py

Python
The first file rasppi.py is a Python program that will be running on the Raspberry Pi. When this program is run, it will store the temperature to the database and publishing it to a topic so that the flask can subscribe to it. The raspberry pi also subscribe the the telegram command publish by the flask app. As we have 3 RPIs we have 1 rasppi.py file on each RPI. The only difference is the room id on line 14 and 31.
import sys
import time
import boto3
import telepot
import MySQLdb
import botocore
import picamera
import Adafruit_DHT
import mysql.connector
from time import sleep
from gpiozero import Buzzer, MotionSensor
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

roomId = 1

# Create an S3 resource
s3 = boto3.resource('s3')

pin = 4
buzzer = Buzzer(5)
camera = picamera.PiCamera()
pir = MotionSensor(26, sample_rate=5, queue_len=10)
my_bot_token = '584706460:AAEdAFpyF6kdmhE-BEVjG2qdxjJy-iRz2fM'
bot = telepot.Bot(my_bot_token)

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

aws = AWSIoTMQTTClient("raspPiRoom1")
aws.configureEndpoint(host, 8883)
aws.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
aws.connect()


def openDbConnection():
    try:
        conn = MySQLdb.connect("iotca2.ca89pfl9pcuj.ap-southeast-1.rds.amazonaws.com", "iotuser", "iotpassword",
                               "homesecure")
    except Exception as e:
        print(str(e))
    finally:
        return conn


# Set the filename and bucket name
bucket_name = 'homesecure-iot'
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={
        'LocationConstraint': 'ap-southwest-1'})


def buzzerOn():
    buzzer.beep()
    return "Buzzer is on"


def buzzerOff():
    buzzer.off()
    return "Buzzer is off"


def getTemperature():
    humidity, temperature = Adafruit_DHT.read_retry(11, pin)
    return temperature


def getHumidity():
    humidity, temperature = Adafruit_DHT.read_retry(11, pin)
    return humidity


def takePhoto():
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        timestring = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
        timeNow = str(time.time())
        camera.capture('/home/pi/CA2/Photo/' + timeNow + 'telegram.jpg')
        print('Photo taken')

        full_path = '/home/pi/CA2/Photo/' + timeNow + 'telegram.jpg'
        file_name = str(timeNow) + 'telegram.jpg'
        s3.Object(bucket_name, str(file_name)).put(Body=open(full_path, 'rb'), ACL='public-read')

        link = 'https://s3-ap-southeast-1.amazonaws.com/homesecure-iot/' + file_name
        root = 'telegram'
        sql = ("INSERT into S3 (pid, link, root) VALUES (%s, %s, %s)")
        data_sql = (str(roomId), str(link), str(root))
        curs.execute(sql, data_sql)
        conn.commit()
    except Exception as e:
        print("Error in take photo : " + str(e))
    finally:
        curs.close()
        conn.close()
    return timeNow


def motionDetection():
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        sql = ("SELECT motionDetection FROM settings WHERE pid = 1")
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            motionDetection = row[0]
            print(motionDetection)

        if motionDetection:
            sql = ("SELECT chatID FROM chatId")
            curs.execute(sql)
            result_set = curs.fetchall()
            for row in result_set:
                chatId = row[0]

            timestring = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
            timeNow = str(time.time())
            camera.capture('/home/pi/CA2/Photo/' + timeNow + 'motionDetected.jpg')
            print('Photo taken')

            full_path = '/home/pi/CA2/Photo/' + timeNow + 'motionDetected.jpg'
            file_name = str(timeNow) + 'motionDetected.jpg'
            s3.Object(bucket_name, str(file_name)).put(Body=open(full_path, 'rb'), ACL='public-read')

            link = 'https://s3-ap-southeast-1.amazonaws.com/homesecure-iot/' + file_name
            root = 'motionDetected'
            sql = ("INSERT into S3 (pid, link, root) VALUES (%s, %s, %s)")
            data_sql = (str(roomId), str(link), str(root))
            curs.execute(sql, data_sql)
            conn.commit()

            bot.sendMessage(chatId, 'Motion have been detected!')
            bot.sendPhoto(chatId, photo=open('/home/pi/CA2/Photo/' + timeNow + 'motionDetected.jpg', 'rb'))
    except Exception as e:
        print("Error in motionDetection : " + str(e))
    finally:
        curs.close()
        conn.close()

def buzzerControl(client, userdata, message):
    if message.payload == 'onBuzzer':
        buzzerOn()
    elif message.payload == 'offBuzzer':
        buzzerOff()


def subTelegram(client, userdata, message):
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        sql = ("SELECT chatID FROM chatId")
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            chatId = row[0]

        if message.payload == 'onBuzzer':
            bot.sendMessage(chatId, buzzerOn())
            buzzerStatus = 'on'
            aws.publish("sensors/buzzer/status/room" + str(roomId), buzzerStatus, 1)
        elif message.payload == 'offBuzzer':
            bot.sendMessage(chatId, buzzerOff())
            buzzerStatus = 'off'
            aws.publish("sensors/buzzer/status/room" + str(roomId), buzzerStatus, 1)
        elif message.payload == 'getTemp':
            bot.sendMessage(chatId, getTemperature())
        elif message.payload == 'getHumidity':
            bot.sendMessage(chatId, getHumidity())
        elif message.payload == 'takePhoto':
            bot.sendMessage(chatId, 'Photo Taken')
            bot.sendPhoto(chatId, photo=open('/home/pi/CA2/Photo/' + takePhoto() + 'telegram.jpg', 'rb'))
    except Exception as e:
        print("Error in subTelegram : " + str(e))
    finally:
        curs.close()
        conn.close()

def pubTemperatureRecord():
    humidity, temperature = Adafruit_DHT.read_retry(11, pin)
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        if temperature != None:
            sql = ("INSERT into temperature (temperature, pid) VALUES (%s, %s)")
            data_sql = (str(temperature), str(roomId))
            curs.execute(sql, data_sql)
            conn.commit()
            aws.publish("sensors/temperature/room" + str(roomId), str(temperature), 1)
    except Exception as e:
        print("Error in pubTemperatureRecord : " + str(e))


aws.subscribe("sensors/telegram/room" + str(roomId), 1, subTelegram)
aws.subscribe("sensors/buzzer/room" + str(roomId), 1, buzzerControl)

while True:
    pubTemperatureRecord()
    if pir.motion_detected:
        motionDetection()
    sleep(5)

app.py

Python
app.py is a Python flask program that will be hosted on EC2. When this program is run, a user can access the web server via a browser such as Chrome and be able to control and view certain things. Such as controlling the switch for the buzzer. Viewing the values of the temperature data that is stored in the database, and output the data as a real-time graph using Google Charts api. And lastly edit the telegram commands and motion detection. Motion detection can be switch on or off to activate the motion sensors and when there is motion detected, a image will be captured through the picam and send to the user through telegram. The app.py also contains the connection to the telegram and sending the command the the different raspberry pi throught the MQTT protocol.
import telepot as telepot
from flask import Flask, render_template, Response,jsonify,request,flash,redirect,url_for
from random import *
import MySQLdb
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
import threading
import time
import json
import sys
import datetime

app = Flask(__name__)
my_bot_token = '584706460:AAEdAFpyF6kdmhE-BEVjG2qdxjJy-iRz2fM'

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

aws = AWSIoTMQTTClient("appFlask")
aws.configureEndpoint(host, 8883)
aws.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
aws.connect()


def openDbConnection():
    try:
        conn = MySQLdb.connect("iotca2.ca89pfl9pcuj.ap-southeast-1.rds.amazonaws.com", "iotuser", "iotpassword", "homesecure")
    except Exception as e:
        print(str(e))
    finally:
        return conn

tempRoom1 = 0
tempRoom2 = 0
tempRoom3 = 0

buzzerStatusRoom1 = 0
buzzerStatusRoom2 = 0
buzzerStatusRoom3 = 0


buzzerStatus1 = 0
buzzerStatus2 = 0
buzzerStatus3 = 0

tempList1 = []
tempList2 = []
tempList3 = []

dateTimeList1 = []
dateTimeList2 = []
dateTimeList3 = []

app = Flask(__name__)



def respondToMsg(msg):
    chat_id = msg['chat']['id']
    command = msg['text']
    topic = "sensors/telegram/"

    print('Got command: {}'.format(command))
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        # For room 1
        sql = ("SELECT * FROM settings WHERE pid = 1")
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            onBuzzerCommand = row[2]
            offBuzzerCommand = row[3]
            takePhotoCommand = row[4]
            getTempCommand = row[5]
            getHumidityCommand = row[6]

        # For room 2
        sql = ("SELECT * FROM settings WHERE pid = 2")
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            onBuzzerCommand2 = row[2]
            offBuzzerCommand2 = row[3]
            takePhotoCommand2 = row[4]
            getTempCommand2 = row[5]
            getHumidityCommand2 = row[6]

        sql = ("SELECT * FROM settings WHERE pid = 3")
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            onBuzzerCommand3 = row[2]
            offBuzzerCommand3 = row[3]
            takePhotoCommand3 = row[4]
            getTempCommand3 = row[5]
            getHumidityCommand3 = row[6]

        if command == onBuzzerCommand:
            payload = 'onBuzzer'
            aws.publish(topic + "room1", payload, 1)
        elif command == offBuzzerCommand:
            payload = 'offBuzzer'
            aws.publish(topic + "room1", payload, 1)
        elif command == getTempCommand:
            payload = 'getTemp'
            aws.publish(topic + "room1", payload, 1)
        elif command == getHumidityCommand:
            payload = 'getHumidity'
            aws.publish(topic + "room1", payload, 1)
        elif command == takePhotoCommand:
            payload = 'takePhoto'
            aws.publish(topic + "room1", payload, 1)

        elif command == onBuzzerCommand2:
            payload = 'onBuzzer'
            aws.publish(topic + "room2", payload, 1)
        elif command == offBuzzerCommand2:
            payload = 'offBuzzer'
            aws.publish(topic + "room2", payload, 1)
        elif command == getTempCommand2:
            payload = 'getTemp'
            aws.publish(topic + "room2", payload, 1)
        elif command == getHumidityCommand2:
            payload = 'getHumidity'
            aws.publish(topic + "room2", payload, 1)
        elif command == takePhotoCommand2:
            payload = 'takePhoto'
            aws.publish(topic + "room2", payload, 1)

        elif command == onBuzzerCommand3:
            payload = 'onBuzzer'
            aws.publish(topic + "room3", payload, 1)
        elif command == offBuzzerCommand3:
            payload = 'offBuzzer'
            aws.publish(topic + "room3", payload, 1)
        elif command == getTempCommand3:
            payload = 'getTemp'
            aws.publish(topic + "room3", payload, 1)
        elif command == getHumidityCommand3:
            payload = 'getHumidity'
            aws.publish(topic + "room3", payload, 1)
        elif command == takePhotoCommand3:
            payload = 'takePhoto'
            aws.publish(topic + "room3", payload, 1)

        elif command == 'active telegram':
            sql = ("INSERT into chatId (ChatID) VALUES (%s)")
            data_sql = (str(chat_id))
            curs.execute(sql, data_sql)
            conn.commit()
        else:
            bot.sendMessage(chat_id, 'No such command')
    except Exception as e:
        print("Error in respondToMsg() : " + str(e))


def subTemperatureRoom1(client, userdata, message):
    global tempRoom1
    tempRoom1 = message.payload


def subTemperatureRoom2(client, userdata, message):
    global tempRoom2
    tempRoom2 = message.payload


def subTemperatureRoom3(client, userdata, message):
    global tempRoom3
    tempRoom3 = message.payload

def subBuzzerStatusRoom1(client, userdata, message):
    print("subbuzzer1")
    global buzzerStatusRoom1
    payload = message.payload
    print(str(payload))
    if payload == 'on':
        buzzerStatusRoom1 = 1
    else:
        buzzerStatusRoom1 = 0


def subBuzzerStatusRoom2(client, userdata, message):
    print("subbuzzer2")
    global buzzerStatusRoom2
    payload = message.payload
    if payload == 'on':
        buzzerStatusRoom2 = 1
    else:
        buzzerStatusRoom2 = 0

def subBuzzerStatusRoom3(client, userdata, message):
    print("subbuzzer3")
    global buzzerStatusRoom3
    payload = message.payload
    if payload == 'on':
        buzzerStatusRoom3 = 1
    else:
        buzzerStatusRoom3 = 0


bot = telepot.Bot(my_bot_token)
bot.message_loop(respondToMsg)
print('Listening for RPi commands...')

aws.subscribe("sensors/temperature/room1", 1, subTemperatureRoom1)
aws.subscribe("sensors/buzzer/status/room1", 1, subBuzzerStatusRoom1)

aws.subscribe("sensors/temperature/room2", 1, subTemperatureRoom2)
aws.subscribe("sensors/buzzer/status/room2", 1, subBuzzerStatusRoom2)

aws.subscribe("sensors/temperature/room3", 1, subTemperatureRoom3)
aws.subscribe("sensors/buzzer/status/room3", 1, subBuzzerStatusRoom3)

def getImagesFromDB(pid,root):
    roomsImages = []
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        sql = ("SELECT * FROM S3 where pid = (%s) AND root=(%s)")
        data_sql = (str(pid), str(root))
        curs.execute(sql,data_sql)
        result_set = curs.fetchall()
        for row in result_set:
            roomsImages.append(row[2])
    except Exception as e:
        print("Error in getImagefromdb " + str(e))
    return roomsImages

def getSettingsFromDB():
    settings = []
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        sql = ("SELECT * FROM settings")
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            sid = row[0]
            pid = row[1]
            onBuzzerCommand = row[2]
            offBuzzerCommand = row[3]
            takePhotoCommand = row[4]
            getTempCommand = row[5]
            getHumidityCommand = row[6]
            getMotionDetection = row[7]
            settings.append({'id':sid,'pid':pid,'onBuzzer':onBuzzerCommand,'offBuzz':offBuzzerCommand,'takePhoto':takePhotoCommand,'getTemp':getTempCommand,'getHumidity':getHumidityCommand,'getMotion':getMotionDetection})

    except:
        print("Error in getSettignsFromDb")

    finally:
        curs.close()

    return settings;

@app.route("/")
def index():
    del tempList1[:]
    del dateTimeList1[:]
    del tempList2[:]
    del dateTimeList2[:]
    del tempList3[:]
    del dateTimeList3[:]
    getTempFromDB()
    imageMotion1 = getImagesFromDB(1,"motionDetected")
    imageTelegram1 = getImagesFromDB(1,"telegram")
    imageMotion2 = getImagesFromDB(2,"motionDetected")
    imageTelegram2 = getImagesFromDB(2,"telegram")
    imageMotion3 = getImagesFromDB(3,"motionDetected")
    imageTelegram3 = getImagesFromDB(3,"telegram")
    templateData = {
        'tempRoom1': tempRoom1,
        'tempRoom2': tempRoom1,
        'tempRoom3': tempRoom3,
        'buzzerStatusRoom1': buzzerStatusRoom1,
        'buzzerStatusRoom2': buzzerStatusRoom2,
        'buzzerStatusRoom3': buzzerStatusRoom3,
        'buzzerStatus1': buzzerStatus1,
        'buzzerStatus2': buzzerStatus2,
        'buzzerStatus3': buzzerStatus3,
        'imageMotion1':imageMotion1,
        'imageMotion2':imageMotion2,
        'imageMotion3':imageMotion3,
        'imageTelegram1':imageTelegram1,
        'imageTelegram2':imageTelegram2,
        'imageTelegram3':imageTelegram3,
        'tempList1':tempList1,
        'tempList2':tempList2,
        'tempList3':tempList3,
        'dateTimeList1':dateTimeList1,
        'dateTimeList2':dateTimeList2,
        'dateTimeList3':dateTimeList3,
    }
    return render_template('index.html', **templateData)

def getTempFromDB():
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        print("getTempFromDB")
        sql = "SELECT * from temperature WHERE pid='1' ORDER BY dateTime DESC LIMIT 10"
        curs.execute(sql)
        result_set = curs.fetchall()

        for row in result_set:
            tempList1.append(str(row[1]))
            dateTimeList1.append(datetime.datetime.strftime(row[2], '%b %d %Y %r'))

        sql = "SELECT * from temperature WHERE pid='2' ORDER BY dateTime DESC LIMIT 10"
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            tempList2.append(str(row[1]))
            dateTimeList2.append(datetime.datetime.strftime(row[2], '%b %d %Y %r'))


        sql = "SELECT * from temperature WHERE pid='3' ORDER BY dateTime DESC LIMIT 10"
        curs.execute(sql)
        result_set = curs.fetchall()
        for row in result_set:
            tempList3.append(str(row[1]))
            dateTimeList3.append(datetime.datetime.strftime(row[2], '%b %d %Y %r'))

    except Exception as e:
        print("Error in gettempfromdb " + str(e))

@app.route('/readTemperature/<room>')
def readTemperature(room):
    if room == 1:
        global tempList1
        global dateTimeList1
        del tempList1[:]
        del dateTimeList1[:]
    if room == 2:
        global tempList2
        global dateTimeList2
        del tempList2[:]
        del dateTimeList2[:]
    if room == 3:
        global tempList3
        global dateTimeList3
        del tempList3[:]
        del dateTimeList3[:]
    tempList = []
    dateTimeList = []
    conn = openDbConnection()
    curs = conn.cursor()
    try:
        sql = ("SELECT * FROM temperature where pid = (%s) ORDER BY dateTime DESC LIMIT 10")
        data_sql = (str(room))
        curs.execute(sql, data_sql)
        result_set = curs.fetchall()
        for row in result_set:
            tempList.append(str(row[1]))
            dateTimeList.append(datetime.datetime.strftime(row[2], '%b %d %Y %r'))
    except Exception as e:
        print("Error in readTemperature " + str(e))
    finally:
        curs.close()

        print("return readtemperature/")
    return jsonify({'temperature' : tempList , 'dateTime': dateTimeList})

@app.route("/buzzer/<room>/<status>")
def writeBuzzer(room,status):
    global buzzerStatus1
    global buzzerStatus2
    global buzzerStatus3
    print("/buzzer/room :"+room)
    if status == 'on':
        payload = 'onBuzzer'

        aws.publish("sensors/buzzer/room" + room, payload, 1)
        if room == "1":
            buzzerStatus1 = 1
        elif room =="2":
            buzzerStatus2 = 1
        else:
            buzzerStatus3 = 1
    else:
        payload = 'offBuzzer'
        aws.publish("sensors/buzzer/room" + room, payload, 1)
        if room == "1":
            buzzerStatus1 = 0
        elif room == "2":
            buzzerStatus2 = 0
        else:
            buzzerStatus3 = 0
    return redirect(url_for('.index'))

@app.route('/settings', methods=['POST', 'GET'])
def setting():
    if request.method == 'POST':
        conn = openDbConnection()
        curs = conn.cursor()
        try:

            print(request.form)
            settingId = request.form.get('settingId','')
            onBuzzerCommand = request.form.get('onBuzzerRoom', '')
            offBuzzerCommand = request.form.get('offBuzzerRoom', '')
            takePhotoCommand = request.form.get('takePhotoRoom', '')
            getTempCommand = request.form.get('getTempRoom', '')
            getHumidityCommand = request.form.get('getHumidityRoom', '')
            motionDetection = request.form.get('motionDetectionRoom', '')



            if onBuzzerCommand == offBuzzerCommand or onBuzzerCommand == takePhotoCommand or onBuzzerCommand == getTempCommand \
                    or onBuzzerCommand == getHumidityCommand or offBuzzerCommand == takePhotoCommand or offBuzzerCommand == getTempCommand \
                    or offBuzzerCommand == getHumidityCommand or takePhotoCommand == getTempCommand or takePhotoCommand == getHumidityCommand \
                    or getTempCommand == getHumidityCommand:
                flash('Value cannot be the same', 'danger')

                return redirect(url_for('.setting'))



            sql = ("UPDATE settings SET onBuzzer = (%s), offBuzzer = (%s), takePhoto = (%s), getTemp = (%s), getHumidity = (%s), motionDetection = (%s)  WHERE settingsid = (%s)")
            data_sql = (str(onBuzzerCommand), str(offBuzzerCommand), str(takePhotoCommand), str(getTempCommand),
                        str(getHumidityCommand), str(motionDetection), (str(settingId)))
            result = curs.execute(sql, data_sql)

            conn.commit()

            flash('Changes saved', 'success')
        except Exception as e:
            flash('A value already existed in the database', 'danger')
            return redirect(url_for('.setting'))

        return redirect(url_for('.setting'))

    elif request.method == 'GET':
        conn = openDbConnection()
        curs = conn.cursor()
        try:
            sql = ("SELECT * FROM settings WHERE pid = 1")
            curs.execute(sql)
            result_set = curs.fetchall()
            for row in result_set:
                settingId1 = row[0]
                onBuzzerCommand1 = row[2]
                offBuzzerCommand1 = row[3]
                takePhotoCommand1 = row[4]
                getTempCommand1 = row[5]
                getHumidityCommand1 = row[6]
                motionDetection1 = row[7]

            sql = ("SELECT * FROM settings WHERE pid = 2")
            curs.execute(sql)
            result_set = curs.fetchall()
            for row in result_set:
                settingId2 = row[0]
                onBuzzerCommand2 = row[2]
                offBuzzerCommand2 = row[3]
                takePhotoCommand2 = row[4]
                getTempCommand2 = row[5]
                getHumidityCommand2 = row[6]
                motionDetection2 = row[7]
            sql = ("SELECT * FROM settings WHERE pid = 3")
            curs.execute(sql)
            result_set = curs.fetchall()
            for row in result_set:
                settingId3 = row[0]
                onBuzzerCommand3 = row[2]
                offBuzzerCommand3 = row[3]
                takePhotoCommand3 = row[4]
                getTempCommand3 = row[5]
                getHumidityCommand3 = row[6]
                motionDetection3 = row[7]
        except Exception as e:
            print("error in settings GET Method : " + str(e))
        templateData = {
            'settingId1' : settingId1,
            'onBuzzerRoom1': onBuzzerCommand1,
            'offBuzzerRoom1': offBuzzerCommand1,
            'takePhotoCommandRoom1': takePhotoCommand1,
            'getTempCommandRoom1': getTempCommand1,
            'getHumidityCommandRoom1': getHumidityCommand1,
            'motionDetectionRoom1': motionDetection1,
            'settingId2': settingId2,
            'onBuzzerRoom2': onBuzzerCommand2,
            'offBuzzerRoom2': offBuzzerCommand2,
            'takePhotoCommandRoom2': takePhotoCommand2,
            'getTempCommandRoom2': getTempCommand2,
            'getHumidityCommandRoom2': getHumidityCommand2,
            'motionDetectionRoom2': motionDetection2,
            'settingId3': settingId3,
            'onBuzzerRoom3': onBuzzerCommand3,
            'offBuzzerRoom3': offBuzzerCommand3,
            'takePhotoCommandRoom3': takePhotoCommand3,
            'getTempCommandRoom3': getTempCommand3,
            'getHumidityCommandRoom3': getHumidityCommand3,
            'motionDetectionRoom3': motionDetection3
        }

        return render_template('settings.html', **templateData)
    else:
        return render_template('settings.html')




@app.route('/settings/<id>')
def controllerEdit():
    return render_template("edit-settings.html")

@app.route('/data')
def data():
    return jsonify({'results' : sample(range(1,10),5),'results2' : sample(range(1,10),5)})

if __name__ == "__main__":
  app.secret_key='P@ssw0rd1234'
  app.run(host='0.0.0.0',port=80)  

dashboard.css

CSS
This is under the same folder as app.py
body {
  font-size: .875rem;
}

.error {
 color: red
 }

.feather {
  width: 16px;
  height: 16px;
  vertical-align: text-bottom;
}

/*
 * Sidebar
 */

.sidebar {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 100; /* Behind the navbar */
  padding: 48px 0 0; /* Height of navbar */
  box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}

.sidebar-sticky {
  position: relative;
  top: 0;
  height: calc(100vh - 48px);
  padding-top: .5rem;
  overflow-x: hidden;
  overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
}

@supports ((position: -webkit-sticky) or (position: sticky)) {
  .sidebar-sticky {
    position: -webkit-sticky;
    position: sticky;
  }
}

.sidebar .nav-link {
  font-weight: 500;
  color: #333;
}

.sidebar .nav-link .feather {
  margin-right: 4px;
  color: #999;
}

.sidebar .nav-link.active {
  color: #007bff;
}

.sidebar .nav-link:hover .feather,
.sidebar .nav-link.active .feather {
  color: inherit;
}

.sidebar-heading {
  font-size: .75rem;
  text-transform: uppercase;
}

/*
 * Content
 */

[role="main"] {
  padding-top: 48px; /* Space for fixed navbar */
}

/*
 * Navbar
 */

.navbar-brand {
  padding-top: .75rem;
  padding-bottom: .75rem;
  font-size: 1rem;
  background-color: rgba(0, 0, 0, .25);
  box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
}

.navbar .form-control {
  padding: .75rem 1rem;
  border-width: 0;
  border-radius: 0;
}

.form-control-dark {
  color: #fff;
  background-color: rgba(255, 255, 255, .1);
  border-color: rgba(255, 255, 255, .1);
}

.form-control-dark:focus {
  border-color: transparent;
  box-shadow: 0 0 0 3px rgba(255, 255, 255, .25);
}

/*
 * Utilities
 */

.border-top { border-top: 1px solid #e5e5e5; }
.border-bottom { border-bottom: 1px solid #e5e5e5; }

Credits

Von Christopher Almendral

Von Christopher Almendral

1 project • 0 followers

Comments

Add projectSign up / Login