The safety in the house is very important. This project presents a prototype smart door lock security system which can be used to enhance security of a door.Besides the traditional method door that used a key can be easily open by unauthorized person or burglar if they have the right key. This will allows them to steal the entire valuable thing in the house.
The core idea of the project is to implement an intelligent and Multi Alert Smart Iot based door lock security system, with less user interaction as possible. So, in this project we will build our own security system which can detect if a door/window is opened. The alarm can be activated or de-activated through voice commands via Google assistant and when an intrusion is detected it will also send a mail along with the message on telegram channel to you and your relatives warning them about it. Cool thing is that entire thing runs on cloud so it can be controlled from anywhere in the world.
IOT based project can leads us to another revolution regarding to automation locking security system. Security can be achieved by normal security guard but digitalization is more effective then all of others. Its extraordinary feature is to make your home, industry, schools, colleges, server rooms etc smart and intelligent through a little use of IOT and cloud computing to save time, save human resource and to get good results in reduce efforts. This security system will be a helping hand for all where security is the major concern.
Area where you can use your project or model.
In the following areas you can provide Smart Door Lock Security by using our project.
- Commercial
Office Buildings, Shopping Centres, banks, Server Room, Hotels & Apartments
- Industrial
Office / Warehouses, Industrial Property, Storage Units / Garages, Data
Centres, power plants
- Transport
Airport Terminals, Train, Metro and Bus Stations, Parking Garage, Distribution Centres
- Education
Schools, Universities, Boarding Schools, Libraries, Kindergartens
- Leisure and entertainment
Restaurents, gyms, stadiums
Working PrincipleIOT door lock based system uses Bolt development board which is based on famous ESP8266 Wi-Fi module from Espressif semi-conductor. But here it has its own Bolt firmware running inside it, this helps us to access the GPIO pins (Digital Read/Write, Analog Read, PWM Write) etc through an API provided by bolt.
In our hardware we will have a Hall Effect sensor and magnet mounted to the door. When the door is opened the magnet moves away from the hall sensor and the sensor will detect it and this can be read by the API calls and we can trigger a Buzzer and this alerts to user through male and telegram.To activate the alarm simply say the command (Activate security alarm) to your Google assistant which have set in IFTTT. Once activated the orange light will start glowing indicating the status. Now, whenever the door is opened the alarm will go high with buzzer sound and also a mail will be sent to your Gmail inbox along with the messge on Telegram Channel with the date and time of the breach.
Setting up the Bolt IoT Module
Before we proceed from here we have to set-up the Bolt hardware. It is very easy to do it, just install the bolt application on your phone and enter your Wi-Fi credentials so that your bolt could connect to your Wi-Fi and thus to the internet. Then you can visit the cloud page to get your Device ID and API key from there you are all good to go. You can visit the BoltIOT docs to know more about it.
Using the GPIO pins of the Bolt IoT hardware
As I said earlier, all the GPIO pins of the Bolt hardware are connected to the cloud and they can be controlled (read/write) only through the API. The API details can be found in the docs that I shared earlier. But let’s look into one as example. The API to read the status of the pin is explained in docs as shown below
Here, what we are interested in this is API URL
Here the API key is 44b2de6b-7e68-40e7-a27f-814b58afe008 and the device ID is BOLT13819450. But this is an example key and ID and will not be the same for your device. You have to visit cloud.boltiot.com to get the Device ID and API key of your device. The below snapshot can help you with that.
Once you get the API key and Device ID you simply have to replace the default values with your value and load the URL in your browser. You browser will respond back with the status of the pin with
{"success": "1", "value": "1"} or {"success": "1", "value": "0"}
If the value is 1 then it’s a high and if 0 then it is a low. Similarly you can try the API links for all the commands like Digital Read, Write, Analog Write, PWM and even serial communication. Once you are done playing with it lets proceed with the actual program for this project.
Preparing the Python EnvironmentAs I told earlier bolt can be programmed with JavaScript, HTML or Python. Here we will concentrate only on how to do it with python. We have to write the python script on our computer for which python should have been installed already. If you are new with all this I would advice reading this article to know how to install python and get started with it. Apart from that we also need to install two library packages in order for our program to work. You can add package to python using the pip install option, run the below commands on you terminal in python directory to install the packages. Open the windows terminal and navigate to the python directory mostly in the C://Python 3
Step 1:- Install pip if you have not installed before. Install it with below command
sudo easy_install pip
Step 2:- Inside the C://Python/Scripts directory install the requests package
pip install requests
Step 3:- The install the boltiot package using the below command
pip install boltiot
Once the installation is finished successfully your careen should look something like this below
That is it now we have open Python IDLE and start writing our actual program for our security system. But before that to activate or de-activate the alarm through Google assistant and to send E-mail and send message to our telegram channel we use the Google Assistant service and Web hooks service provided by IFTTT. So let’s go ahead and set them now. If you are new with using IFTTT applets then it is recommended to read this article before proceeding.
Activating and De-activating the alarm using the Google AssistantWe have to create two applets (recipes) for this, one is to activate the alarm and the other is to de-activate the alarm. When the alarm is activated the capacitor connected to pin 3 should be charged and when the alarm is de-activated the capacitor connected to pin 4 should be charged.
The applet uses Google assistant for this service and web hooks get request for that service. The below screen shot shows how the applet is set for making the pin 3 high when Activating the alarm and making the Pin 4 High when deactivating the alarm through Google assistant.
The Capacitor 1 and 2 is used as memory elements. When the board receives command from the IFTTT the pin 3 and 4 will act as output pin. Based on the command the board will charge either the Capacitor 1 or the Capacitor 2.
Now when the IFTTT operation is completed the Python code makes the pin 3 and 4 as input pin, by reading the status of these pins the python code will understand if it should activate or deactivate the alarm based on which capacitor has charge. Simply put it is a small hack to interface the IFTTT with Python. It would have been a lot easier if Bolt platform has provided a virtual bit but said that is not an option here.
Sending E-mail when Intruder is detected
The third applet would be to send an E-mail when the intruder is detected. This can be done by using the web hooks and Gmail service on IFTTT. The Webhooks service will give us a URL which when loaded will trigger that pre-defined Email. The snapshot of the applet is shown below. You can customize the receiver ID and text as you wish. This URL will then be triggered in the python script using the requests library if an intruder is detected.
Sending Alert to Telegram Channel when Intruder is detected.
1. We will be making use of the telegram channel to broadcast alerts when any intruder is detected.
2. First, create a new channel in telegram and provide a suitable name and description as shown below.
3. In the next screen set the channel as Public and also enter the channel permanent link as per your wish. Save this channel link as “telegram_chat_id”, wherein below image its “smart_door_lock_alarm".
4. Now let’s create a bot for our channel. A bot is a third-party application that runs inside the telegram, we will use this bot to send alerts to our channel.
5. On the home screen of telegram, click on the search icon on the top right corner and search for botfather.
6. In search results, select the botfather which has a blue tick mark next to it.
7. The chat shows few possible commands, type “/newbot” to create a new bot.
8. Give proper name and username to your bot.
9. Once the bot is created successfully it generates a token. This token is used to send and receive messages through python.
10. Please save this note as “telegram_bot_id” where it is saved as “bot” followed by bot token.
11. Now let’s add the bot to our channel, go to channel description and select add administrator from 3 dot menu. Choose the bot from the search field and give proper rights to the bot.
Select Add administator
12.Congratulations! You have successfully created a channel and a bot.
The complete python code for this IoT Security Alarm can be found at the end of this project. In this section let’s break the code into small snippets and try to understand them. The overall aim of the python script is to check if the alarm is activated or de-activated and if activated we have to check if the door is opened and if opened we have to trigger an E-mail and turn on the buzzer.
We already know that the capacitor on pin 3 will be high if we have to activate the security system and the capacitor on pin 4 will be high if we have to de-activate the security system. So we simply have to read them in our python script to activate or de-activate the alarm.
We begin the program by importing the time, json,requests and boliot library. Out of which the time library is added in python by default, but you have to manually install the requests and boltiot packages as we discussed earlier else you will get an error on these lines.
import time #Import time to peform delay operations
import requests #use requests to send mail via webhooks IFTTT
from boltiot import Bolt #Import boliot to control GPIO pins through API
import json # library for handling JSON data
Next we enter the credentials of the device such as the API key and the Device ID. Only with these two values you can access any GPIO pin on the device. Do not share these with public if since they can be used by anyone to control your GPIO pins.
api_key = "4749fe75-6c61-45f1-bee5-f9a6a1bd9103" #Get your API key from Blot Cloud Web
site
device_id = "BOLT11691968" #Get your Bolt device ID form Bolt Cloud Website
mybolt = Bolt(api_key, device_id)
telegram_chat_id = "@XXXX" # This is the channel ID of the created Telegram channel.
Paste after @ symbol.
telegram_bot_id = "botXXXX" # This is the bot ID of the created Telegram Bot. Paste
after bot text.
As discussed on the API section we will get response when we perform a digital Read in the form of string, so I have assigned those string values to two variables so that we can use them in our program easily.
HIGH = '{"value": "1", "success": "1"}' #This will be returned by bolt API if digital read is high
LOW = '{"value": "0", "success": "1"}'#This will be returned by bolt API if digital read is low
Now we make a function named as send_telegram_message() which takes message as a parameter.
In the first line, we are building the URL so that Telegram knows which bot it has to send the message to. The telegram_bot_id is required for this purpose.The data variable is a dictionary which holds the chat ID(Channel ID) so that the Bot knows which channel it has to post the message to. It also contains the text message to be sent as a message.
In the next step, we need to make a HTTP request to the Telegram servers using the URL we have built earlier. The request is a "POST" request which contains all the relevant data like URL and the data to be contained in the request.
The line `telegram_data = json.loads(response.text)` converts the text response to a JSON object and stores it in telegram_data.The status of the request is stored in the "ok" field of the telegram_data variable and we are returning it. The "ok" field will always contain a boolean value i.e. True/False and is True if the message has been sent.
The function is encased in a try-except block so that any errors are caught and it returns a False if any error is present in the try block.
def send_telegram_message(message):
"""Sends message via Telegram"""
url = "https://api.telegram.org/" + telegram_bot_id + "/sendMessage"
data = {
"chat_id": telegram_chat_id,
"text": message
}
try:
response = requests.request("POST",url,params=data)
telegram_data = json.loads(response.text)
return telegram_data["ok"]
except Exception as e:
print("An error occurred in sending the alert message via Telegram")
print(e)
return False
Inside the infinite while loop, we have two other loops. One will be executed if the alarm is activated from the Google assistant and the other will be executed if the alarm is de-activated. By default the de-activated loop will be executed if no command is received.
Here, have to check if the alarm is activated by reading the pin 3 which is nothing but the capacitor. If the pin is high we make the orange LED to glow and then exit this loop and get into activated while loop. We check this for every 5 seconds just to make sure that we do not exceed the API rate limit provided by bolt, which is 30 calls per minute.
while alarm == 0: #If alarm is off
response = mybolt.digitalRead('3') #check if it is being activated
if (response == HIGH):
print("Security System is activated")
mybolt.digitalWrite('2', 'HIGH') #Turn on LED to indicate Alarm is
activated
mybolt.digitalWrite('4','LOW') #Turn off the capacitor of the 4 pin
alarm = 1
elif (response == LOW):
print ("Waiting for Security System to be activated....")
else:
print ("Problem in getting value form pin 3")
time.sleep(2) #check once in every 2 seconds to avoid exceeding API rate limit
Similarly, inside the activated while loop, we have to check for pin 4 to know if the alarm is being de-activated. If de-activated we turn off the orange loop and get back to the de-activated while loop. Else we have to check the magnet if it is present close to the hall sensor by reading the pin 0. If the pin is high then it means that magnet is away from the sensor indicating that the door has been opened. So we have trigger the buzzer and also trigger the mail and message to Telegram channel using the requests package. Else we keep monitoring the sensor for every 5 seconds. The code to do the same is shown below
while alarm == 1: #If alarm is on
response = mybolt.digitalRead('4') #check is it is being de-activated
if (response == HIGH):
print("Security System is De-activated")
mybolt.digitalWrite('2', 'LOW')#Turn off LED to indicate Alarm is
De-activated
mybolt.digitalWrite('3', 'LOW')#Turn off the 3 GPIO pin.
alarm = 0
break
elif (response == LOW):
print ("Security System is currently active can be deactivated from google
assistant")
else:
print ("Problem in getting value form pin 4")
response = mybolt.digitalRead('0') #check if hall sensor is triggered
if (response == HIGH): #if magnet is not present
print ("Alert! Security breach Buzzer ON")
mybolt.digitalWrite('1', 'HIGH')
requests.get('https://maker.ifttt.com/trigger/Breach/with/key/i6nPcZ5ZlzaV
dbYITw6VGcpMkrVO5GqAX049cHEBDt') # webhook link to trigger mail through IFTTT
telegram_status=send_telegram_message("Alert!Someone opens your secret
door")
print("This is the telegram status: ",telegram_status)
time.sleep(5)
mybolt.digitalWrite('1', 'LOW')
print ("Buzzer OFF")
elif (response == LOW):
print ("No problem, all good!")
else:
print ("Problem in reading the value of button")
time.sleep(5)
Time to test the DeviceOnce you are ready with the code we can start testing our project. Mount the board on the door’s frame and the magnet on the door itself. Make sure that the magnet stays close to the hall sensor. The idea is that the sensor should detect the magnet when door is closed and should not be able to detect the magnet when the door is opened.
Project Video showing the final output:-
Comments