Technology makes our lives easier. When need arises, so does tech and this project, The Time Saver is all about making our day to day activities a notch easier than it already is by integrating some of the most important parts of our lives.
"The advance of technology is based on making it fit in so that you don't really even notice it, so it's part of everyday life." - Bill Gates
A product or device becomes all the more appealing when it performs various functions and turns out looking like an all in one packaged deal which is the basic idea behind this project.
Day to day activities such as checking the weather before an errand, protection from theft, investment checks are made easier by this project that's also known as "The Time Saver".
IntroductionThe Time saver project can do the following functions:
- Burglar Detection along with an alarm, call and SMS
- Weather and temperature condition check aka rain check
- Alerts you when the Cryptocurrency's (here, bitcoin) value increases by a specific percent.
Burglar detection
The burglar detection is done using a sensor known as a passive infrared sensor (PIR) and is made up of a pyroelectric sensor.
The sensor has two modes. I'll be using it in the non-repeatable mode (default mode) to change it you have to place the retrigger setting jumper on the other two pins. Adjust your delay time and sensitivity according to your preferences refer to the images given below. The value increases when you turn it in the clockwise direction. To know more about the working - electronic wings/pir-sensor
The buzzer is activated once, motion is detected. It can be configured to sound the alarm in a frequency of your choice. A text alert and a call is also sent to your number via Twilio (link in online services).
Weather Check
You would have to sign up with OpenWeatherMap - openweathermap link you'll receive the required API key in the email ID that you've provided, save it for future use. The buzzer will switch on if you need to carry an umbrella or if the temperature is extreme, along with a text notification of the weather description and temperature. An sms consisting of the weather description and the maximum temperature of the day will be sent even if there's no weather alert. Its configured to perform a weather check only if the user pushes a button for two seconds, when prompted.
Cryptocurrency value
The Rest API is used for this function. min-api.cryptocompare is used to check the current price of the cryptocurrency of your choice (here, bitcoins) and get notified if its value increases as then, it would be the right time to invest in them also, to notify all your friends about the value increase along with the amount of increase that has occurred by just adding them to a group in telegram. The notification is sent only if the value increases by 20% or more, from its preset value.
The preceding, topics will be explained in the following sections.
Step 1: Circuit or hardware connectionCAUTION:Do not perform this step when your module is connected to a power source to avoid shorting the components.
The schematics and pictures of the circuit is as shown:
PIR sensor connection:
- Vcc pin is connected to 5V pin of the bolt module.
- The digital output pin is connected to GPIO pin 1.
- The gnd is connected to the ground/gnd pin of bolt.
Buzzer connection:
- The shorter pin or negative pin is connected to the ground of the bolt.
- The longer pin or positive pin is connected to GPIO pin 0.
Push button connection:
- Any of the two pins in the button is connected to ground.
- The other pin is connected to a 5V output via a resistor (10k ohms) as a power source and connected to GPIO pin 4 (refer schematics if, in doubt).
We will be using the Ubuntu linux terminal as our command line or vmware with Ubuntu ISO installed, if you have windows as your OS. I have created a droplet in Digitalocean via which I'll SSH into but its not necessary. I did it for added security as we'll be using external API's.
Install python 3, requests and the boltiot package in your terminal or command line by executing the following commands:
$ sudo apt-get update
$ sudo apt-get install python3.6
$ sudo apt get-y update
$ sudo apt install python3-pip
$ sudo pip3 install boltiot
$ sudo pip install requests[security]
Troubleshooting - If you are getting Python locale error: unsupported locale setting then run the following commands then select all locales then another pop will open. Select en_US.UTF-8 and press enter.
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales
Flask is used for creating a XML application to make a twiml request when placing a call for the burglar detection system. ngrok - ngrok (download link) is used to host a public URL. Make sure that ngrok is successfully downloaded before executing the code for placing a call. The ngrok free plan is sufficient.
The steps to setup flask may vary. the steps are given in: flask. The steps that were executed for flask installation on Ubuntu python3:
$ mkdir myproject
$ cd myproject
$ python3 -m venv venv
$ . venv/bin/activate #activates the virtual environment
$ pip install Flask #installs Flask
$ pip install twilio #installs twilio packages
Step 3 - getting started with the online services:Bolt platform:
The bolt device API and ID can be found in your bolt cloud account dashboard Cloud dashboard. use this link Cloud API link and save this in a separate file using the nano command.
eg: sudo nano filename.py
Twilio account Setup:
Twilio is the service that we'll be using for sending a SMS or text notification to your number. We'll be using a trial account. Sign up with your email ID and verify your number in which you'll receive the alerts on. The link to sign up for a trial account- https://www.twilio.com/try-twilio
The following link will guide you with your account setup -steps to get started with twilio trial account
Select any number that is prompted by twilio as your number from which you'll receive SMS and call notifications. Save your Auth token, SID, twilio number and yours for future implementation in your code. you'll find them in the twilio dashboard.
OpenWeatherMap setup:
To check for current weather conditions and surrounding temperature you have to sign up with the OpenWeathermap - https://openweathermap.org/ After which you'll receive an api key in your email id save it for future use.
The link that you'll use can be found under API in the current weather data api documentation (refer above image). The link that I used is:
URL = 'http://api.openweathermap.org/data/2.5/weather?q=yourcityname&APPID=yourapikey&units=metric'
The units in metric is added so that temperature is read in celsius.
Copy paste the URL in the search bar and check for an output similar to this:
The parameters of weather are in the first list index in the form of a python dictionary. The output format we'll be using is json. To get a list of weather ID conditions go to this link - ID values under weather condition codes.
Telegram Setup:
Refer to the above picture gallery for the telegram bot and channel setup.
- Download the Telegram App from the playstore.
- In the Menu (left top corner), tap on 'New Channel' option
- Give the channel a name and select the 'Public Channel' option then type a unique permanent link name and save it (after./) for future use (telegram chat id).
- Type BotFather in the search tab. Select the one which has a verified or blue tick symbol.
- Type the /newbot command, then enter the bot name and a unique link for the bot.
- The API token will be shown under the token to access http api (telegram bot id). save it securely and do not share it as, it gives control over your bot.
- Go to the channel that's newly created and make the bot an admin of the channel with most of the permissions.
Save the following in a new file using the nano command with the.py extension. The code for that is given in the next step:
- bolt device ID and API
- Twilio auth token, SID, Twilio number, your number
- telegram chat id and telegram bot id
Cryptocompare for BTC:
I've used this https://min-api.cryptocompare.com/ to return the value of bitcoins (any cryptocurrency). Its not necessary to create an account in the site to perform this action. The REST API Documentation is provided in this link- Rest API documentation. Select execute call to get an output demo from the API.
fsym is an abbreviation for 'from symbol' which represents the symbol of the cryptocurrency (here, BTC) 'to symbol' is abbreviated as tsym which represents the currency type eg: INR, USD etc. The Rest API that's used is:
URL = 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=INR'
Step 4: CodeNote- Do not SSH for the flask app code and for ngrok URL activation. make sure that virtual environment is activated before you execute code
The code for the flask app: refer to the Flask app code given in the code Attachments (last section)
from flask import Flask import deets app = Flask(__name__) from twilio.twiml.voice_response import VoiceResponse, Say @app.route('/call', methods=['GET','POST'])
def call(): response = VoiceResponse() response.say('Burglar Alert!!', voice='Alice', language='en-US',loop=3) response.play( print(response) return str(response) if __name__ == '__main__': app.run(debug=True)
Commands for code execution and file creation:
$ python3 filename.py #execution of code command typed in python3
$ sudo nano filename.py #creating python file in nano editor
After, downloading ngrok (link in software setup) activate the ngrok URL:
$ ./ngrok http 5000
5000 is the local host server in which flask runs on. after, the above code you will see a similar screen:
Copy the URL adjacent to Forwarding (above image) and add app route name (here, /call) at the end, and save it for later use. The output of the ngrok URL:
Note: Flask app code should be running and ngrok session status must be online when you run the code for twilio to place a call.
- Connect the hardware as shown in the schematics
- SSH into the droplet or login into your putty / vmware
- After, login create a file using the nano command and.py extension. save your credentials in the file by CTRL + X (skip this step if done already)
sid = 'You can find SID in your Twilio Dashboard'
auth = 'You can find on your Twilio Dashboard'
fromno = 'This is the no. generated by Twilio. You can find this on your Twilio Dashboard'
tono= 'This is your number. Make sure you are adding +91 in beginning'
devapi = 'This is your Bolt Cloud account API key'
devid = 'This is the ID of your Bolt device'
telegram_bot_id = 'the http request api provided by botfather'
teleram_chat_id = 'the permanent link for your channel after./'
- open another file using the nano command and.py extension to write the main code in it.
- import the necessary modules
import json #library for JSON data handling
import time #module for delay or sleep
import deets #deets.py is the file for api, tokens (above code)
import requests #for HTTP requests
from boltiot import Sms, Bolt #to access bolt data and sms object for alerts
from twilio.rest import Client #to place calls via twilio
Algorithm for the main code:
- Collect the data from the Bolt GPIO pin 1 (PIR sensor output pin)
- Send SMS, place a call and switch on buzzer for 20 seconds if it returns 1 as the value.
- Using the cryptocompare REST API get the current value of bitcoins.
- If the current value is higher than 20 percent of the preset value then send an alert via telegram that includes the increment difference.
- Prompt user to push button for a weather check. If pushed then switch on buzzer for 10 seconds and send sms alert of the weather description if the weather id matches with any form of precipitation or if the temperature is either too hot or cold.
- Send only SMS with weather description and maximum temperature of the day if there is no weather alert.
- Wait for 10 seconds. Repeat from step 1.
The code block for some main functions are given successively, for line by line explanation please check the comments attached in the main code section under Attachments.
Code for accessing weather, temperature data:
URL = 'http://api.openweathermap.org/data/2.5/weather?q=city&APPID=apikey&units=metric'
data = requests.get(URL).json()
weatherr = data['weather'][0]['id']
weatherdescrip = data['weather'][0]['description']
temp = data['main']['temp_max']
Code for placing a Twilio call:
from twilio.rest import Client
import deets
# Your Account Sid and Auth Token from twilio.com/console
account_sid = deets.sid
auth_token = deets.auth
client = Client(account_sid, auth_token)
call = client.calls.create(url='your ngrok url',to=deets.tono,from_=deets.fromno)
print(call.sid)
Code for sending SMS via Twilio:
print("Making request to send a SMS")
response = sms.send_sms("message body")
print("Response received from Twilio is: " + str(response))
print("Status of SMS at Twilio is :" + str(response.status))
Code for sending a Telegram message:
def send_telegram_message(message):
url = "https://api.telegram.org/" + deets.telegram_bot_id + "/sendMessage"
#link for asking your bot to sendmessage
data = {
#the data required is stored in a dictionary
"chat_id": deets.telegram_chat_id,
#the channel id to where the message must be sent
"text": message
#messgae is where the body of the text is stored
}
try:
response = requests.request(
#requests the url to post the message to that channel
"POST",url,params=data)
print("Telegram URL")
print(url)
print("Telegram response")
print(response.text)
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
''' calling this function'''
message = "Alert! its the right time to invest in BTC"
#the alert text that's sent via telegram
telegram_status = send_telegram_message(message)
#function called and status returned
Code for accessing the current BTC value:
def btcpricecheck():
print("checking the current bitcoin price")
try:
URL = 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=INR'
btcresponse = requests.request('GET',URL)
#gets the request from the URL and stores it in btcresponse
btcresponse = json.loads(btcresponse.text)
#loads the request response in a json text format and stores it in btcresponse
instantprice = btcresponse['INR']
#the value of the INR key is stored in instant price
return instantprice
except Exception as e:
print("error occurred while getting btc price")
print(e)
Project Demonstration and Output:Burglar Alarm Demo:
Twilio Call Alert:
Telegram and Twilio text Alerts:
Code Terminal Output:
Comments