Hardware components | ||||||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
![]() |
| × | 1 | |||
Software apps and online services | ||||||
![]() |
| |||||
![]() |
| |||||
![]() |
| |||||
| ||||||
| ||||||
![]() |
|
The project is called HomeSecure. An anti-theft system used to prevent or deter unauthorized appropriation of items considered valuable. It captures an image whenever the PIR sensor detects a motion and sends it to telegram. It also tracks the current temperature of the surrounding area. There is also a website where the users can view the temperature history and the Images captured. Users can control the buzzer using the website as well as edit telegram commands under settings. The telegram can control the buzzer, get current temperature and humidity and capture images using the piCam. This can be done through commands that users have set on the website.
Why did we decide to make it?We create HomeSecure as we believe that, while today's burglary statistics show an overall decrease in burglary rates, thousands of homes (roughly 325, 000) are still being broken into every year - often in plain view, during the day. In fact, property crimes in 2015 resulted in losses estimated at $14.3 billion.
We believe that our project can at least deter crimes related to burglary as we have created a system that allows home protection specially when the there is no one at home.
How does it work?The website is hosted on EC2 and it communicates with the Raspberry Pi through MQTT services provided by Amazon Web Services. The telegram function is also hosted together with the website using the same services.
How to set it up?This is how the final project should look like:
This is how the Fritzing diagram looks like:
Rooms Page
Settings Page
Telegram Bot
In this Step, you will learn how to create and register your Raspberry Pi as a “Thing” with AWS IoT.
- Sign in to your IoT Console.
- Register your Raspberry Pi as a Thing.
- Copy REST API endpoint of your “Thing”
- Create Certificates
- Create a Security Policy for your RPi
- Attach Security Policy and Thing to your Cert
- Install the AWS Python library in your raspberry pi with this command
sudo pip install AWSIoTPythonSDK
Step 3: Code the IoT appIn this step, you will write a simple Python program thatreads the values from your DHT11 and send it to AWS
Create a file named “aws_pubsub.py” with the following code
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
import Adafruit_DHT
pin = 4
# Custom MQTT message callback
def customCallback(client, userdata, message):
print("Received anew message: ")
print(message.payload)
print("from topic:")
print(message.topic)
print("--------------\n\n")
host = "YourEndPoint.amazonaws.com"
rootCAPath = "rootca.pem"
certificatePath = "certificate.pem.crt"
privateKeyPath = "private.pem.key"
my_rpi = AWSIoTMQTTClient("basicPubSub")
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()
my_rpi.subscribe("sensors/temperature", 1, customCallback)
sleep(2)
# Publish to the same topic in a loop forever
loopCount = 0
while True:
humidity, temperature =Adafruit_DHT.read_retry(11, pin)
my_rpi.publish("sensors/temperature",str(temperature), 1)
sleep(5)
Step 4: Run the IoT appRun your program to verify that you canconnect to AWS and publish and receive sensor messages using the MQTT protocolas shown in the instructions below.
- Copy the required Security Files
- Ensure Paho MQTT is installed on your RPi
sudo pip install paho-mqtt
- Run the program
- View MQTT messages
S3 provides a simple web services interfacethat you can use to store and retrieve any amount of data, at any time, fromanywhere on the web. To store data on S3, you will need tocreate an S3 Bucket in a specified AWS region. An S3 bucket serves as a container for you to organise the objects youwant to store in the cloud and has a standard URL for accessing the objects.
- Create a bucket on Amazon S3
- Install Boto on Raspberry Pi
sudo pip install boto3
- Install AWS CLI on Raspberry Pi
sudo pip install awscli
- aws configure
In this section, you will make use of theAccess Key Id and Secret Access Key to run the “aws configure” command so thatyou can successfully use the AWS boto3 Python SDK library to write Pythonprograms that can interact with AWS services like S3, DynamoDB and Rekognitionsuccessfully.
- Code the python file
Create the following file with the Python code below which uses thePicam to take a photo, and then uploads it to Amazon S3. Replace bucket_name with the name of your own S3 bucket. In this instance, we names it boto.py
import boto3
import botocore
from picamera import PiCamera
from time import sleep
# Create an S3 resource
s3 = boto3.resource('s3')
camera = PiCamera()
sleep(5)
full_path = '/home/pi/Desktop/image1.jpg'
file_name = 'image1.jpg'
camera.capture(full_path)
sleep(3)
# Set the filename and bucket name
bucket_name = 'homesecure-iot' # replace with your ownunique bucket name
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-southeast-1'})
# Upload a new file
s3.Object(bucket_name, file_name).put(Body=open(full_path, 'rb'))
print("File uploaded")
#s3.upload_file(full_path,bucket_name, file_name)
- Run the python file you just created
- Check that file is uploaded in S3 Console
In this step, we will be setting up Amazon RDS
- Create a database. We used MySQL for our project.
Specify a name for the database. In this instance, we named it “homesecure-iot”. Create a master username and password. Make sure to remember it as it will be used in the future. Then click on next.
- Enable “Public accessibility” Enable “Create new VPC security group” And then Click “Create”.
- Click on “homesecure-iot” to be redirected to the homesecure-iot instance.
Once in the page, take note of the endpoint and port. Copy it to a notepad.
- Download mySQL workbench
- Install mySQL workbench
- Create a new database in mySQL workbench
Choose any name you desire. Enter the endpoint you have copied earlier under hostname. Enter the port you have copied earlier under port. Enter the username you have copied earlier under username. Then click on OK
- Create a Schema
- Create 5 tables with the following settings
- Create a python file called rdsconnect.py
importMySQLdb
importmysql.connector
try:
db =MySQLdb.connect("homsecure-iot.c9aj9ieaf1e8.ap-southeast-1.rds.amazonaws.com","iotuser", "iotpassword", "homesecure-iot")
curs = db.cursor()
print("Successfully connected todatabase!")
except:
print("Error connecting to mySQLdatabase")
- Run the python program
Step 7: Setting up AWS EC2
- Set up the Ubuntu Server 16.04
- Create a new key pair and name it to anappropriate name. In this instance, we named it “mykeypair”. After naming it, download the key pair and the launch the instance.
- Click on connect.
- Copy the phrase under example as it is important for later.
- Open up a prompt of ssh client. In this case, wewill be using anaconda prompt.
- Using anaconda prompt, go to the directory ofthe folder where you downloaded the mykeypair.pem
- Paste the phrase that you have copied earlier and then press enter. You woll be promted to enter yes or no. Enter Yes.
- Install python in the anaconda prompt.
type sudo apt install python
- Update it
sudo-apt-get update
- Now, for the remaining dependency enter:
sudo apt-get install python-setuptools python-devbuilt-essential –-user
We still have to install 4 more dependencieswhich are Flask, mySQL, Awsiotpythonsdk, and telepot.
- For now enter
curl -O https://bootstrap.pypa.io/get-pip.py
- Install pip by entering the phrase below.
python get-pip.py --user
- Then enter the phrase below
pipinstall flask --user
- Now, install awsiotpythonsdk by entering the phrase below.
pip install AWSIoTPythonSDK -–user
- Install telepot by entering the phrase below.
pip install telepot -–user
- Lastly install mysqlclient which is a little different. Start by enter the phrase below.
sudo apt-get install python-dev libmysqlclient-dev
Enter "Y" or "yes" if there is a prompt.
- Then, install mysqlclient by entering the phrase below.
nowpip install mysqlclient –user
- Finally, Run the Server.
- Transfer the Files to the EC2 instance using Filezilla.
- Go back to your bash prompt then type
sudo python app.py
- Enter your IP address on the browser to access the website.
There is a more detailed document listed below. It contains step by step guide on how to set up the entire project.
The codes needed for the project are also listed below.
index.html
HTML <!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<!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<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{% 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
Pythonimport 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
Pythonimport 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)
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; }
Comments
Please log in or sign up to comment.