Shivani Pothirajan
Published © GPL3+

The Time Saver

Need a device to check for burglars ? regular updates on bitcoin prices and weather conditions before an errand ? if yes, this is for you.

IntermediateFull instructions provided3 hours299

Things used in this project

Hardware components

Bolt WiFi Module
Bolt IoT Bolt WiFi Module
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
Buzzer
Buzzer
×1
Switch Actuator, APEM A01 series Illuminated Push-Button Switches
Switch Actuator, APEM A01 series Illuminated Push-Button Switches
Any push button with two pins is good enough
×1
Resistor 10k ohm
Resistor 10k ohm
×1
Jumper wires (generic)
Jumper wires (generic)
×1
USB-A to Micro-USB Cable
USB-A to Micro-USB Cable
×1

Software apps and online services

Bolt Cloud
Bolt IoT Bolt Cloud
SMS Messaging API
Twilio SMS Messaging API
openweathermap
mini cryptocompare
telegram
Snappy Ubuntu Core
Snappy Ubuntu Core

Hand tools and fabrication machines

Breadboard, 270 Pin
Breadboard, 270 Pin

Story

Read more

Schematics

Hardware connection

Code

Flask application code

Python
Flask application of twiml for placing a call
from flask import Flask   #an instance of this class is the wsgi app 

app = Flask(__name__)

from twilio.twiml.voice_response import VoiceResponse, Say

@app.route('/call', methods=['GET','POST'])

def call():
    print('Invoked')
    response = VoiceResponse()
    response.say('Burglar Alert!!', voice='Alice', language='en-US', loop=3)
    print(response)
    return str(response)

if __name__ == '__main__':   #to run as a pyhton file and enable debugging
    app.run(debug=True)

Main project code

Python
import json, time, deets, requests                      
from boltiot import Sms, Bolt
from twilio.rest import Client

mybolt = Bolt(deets.devapi, deets.devid)
sms = Sms(deets.sid, deets.auth, deets.tono, deets.fromno)
URL = 'http://api.openweathermap.org/data/2.5/weather?q=cityname&APPID=apikey&units=metric'
data = requests.get(URL).json()                              
#requests the data from the URL in json format and stores it in data variable
weatherr = data['weather'][0]['id']                          
#the 0th index of weather list has id key whose value is stored in weatherr 
weatherdescrip = data['weather'][0]['description']  
#same as above but is weather description         
temp = data['main']['temp_max']                              
#main dictionary(no index)in which temp_max is a key whose value is stored in temp variable
currentbtc = 71500                                 #preset btc value in INR
account_sid = deets.sid                            #SID of twilio account
auth_token = deets.auth                            #auth token of twilio account

def weather_check(weather):
   print("checking current weather report")
   try:
        if weather==200 or weather==201 or weather==202 or weather==210 or weather==211 or weather==212 or weather==221 or weather==231 or weather==230 or weather==232:
            print("Forecast  Alert !!")                                      #the above line checks for the weather IDs
            print("Requesting Twilio to send sms")
            response = sms.send_sms("FORECAST ALERT-" + weatherdescrip)      #send_sms function sends the text to twilio and stores response from twilio   
            print("Response from Twilio is: " + str(response))               #prints the response from twilio
            print("Status of SMS at Twilio is :" + str(response.status))     #prints the status of sms 
            mybolt.analogWrite(0,70)       #switches on buzzer with 70 frequency
            time.sleep(10)                 # the buzzer switches on for 10 secs 
            resp = mybolt.analogWrite(0,0)     #swicthes off buzzer 
            data = json.loads(resp)            #gets the json response from bolt
            print(data)                        #prints response in json format
        if weather==500 or weather==501 or weather==502 or weather==503 or weather==504 or weather==511 or weather== 520 or weather== 521 or weather==522 or weather==531:
            print("Forecast Alert!!")
            print("Requesting Twilio to send sms")
            response = sms.send_sms("FORECAST ALERT- " + weatherdescrip)
            print("Response from Twilio is: " + str(response))
            print("Status of SMS at Twilio is :" + str(response.status))
            mybolt.analogWrite(0,50)
            time.sleep(10)
            resp = mybolt.analogWrite(0,0)
            data = json.loads(resp)
            print(data)
        if temp >= 30 or temp <= 20:
            print("Temperature alert!!")
            print("Making request to Twilio to send a SMS")
            response = sms.send_sms("TEMPERATURE ALERT- "+ str(temp))
            print("Response received from Twilio is: " + str(response))
            print("Status of SMS at Twilio is :" + str(response.status))
            mybolt.analogWrite(0,30)
            time.sleep(5)
            mybolt.analogWrite(0,0)
        else:
            print("no weather alerts, weather for today:"+ weatherdescrip)
            print("Making request to Twilio to send a SMS")
            response = sms.send_sms("No weather Alerts. the weather for today- "+ weatherdescrip)
            response = sms.send_sms("maximum temperature for today:"+str(temp))
            print("Response received from Twilio is: " + str(response))
            print("Status of SMS at Twilio is :" + str(response.status))

   except Exception as e:                                                            #handles error if exception e then it gets printed if print(e) is executed 
        print("weather error:")                                           
        print(e)

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 reruest response in a json 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)

def send_telegram_message(message):
    url = "https://api.telegram.org/" + deets.telegram_bot_id + "/sendMessage"          #link for 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                                                                #message 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)        #prints telegram response
        telegram_data = json.loads(response.text)
        return telegram_data["ok"]
    except Exception as e:
        print("An error occurred while sending the alert message via Telegram")
        print(e)
        return False


while True:
    print("Checking for burglars and bitcoin value")
    responsee = mybolt.isOnline()             #checks if bolt device is online
    boltdata = json.loads(responsee)         #loads the response in json format
    boltstatus = boltdata['success']  
    #value of the success key is stored in boltstatus
    if boltstatus != 1:                 #satisfies condition if bolt is offline
       print("device is offline error")        
       break
    print ("Reading sensor value")
    response = mybolt.digitalRead('1')            #reads the value of GPIO pin 1
    data = json.loads(response)               
    print("Sensor value is: " + str(data['value']))     #prints sensor value 
    try: 
        sensor_value = int(data['value']) 
        if sensor_value == 1:                            
            #refer to the comments in weather_check function                            
            resp = mybolt.analogWrite(0,170)
            dataa = json.loads(resp)
            print(data)
            time.sleep(20)
            resp = mybolt.analogWrite(0,0)
            dataa = json.loads(resp)
            print(dataa)
            print("Making request to Twilio to send a SMS")           
            response = sms.send_sms("BURGLAR ALERT: " +str(sensor_value))
            print("Response received from Twilio is: " + str(response))
            print("Status of SMS at Twilio is :" + str(response.status))
            client = Client(account_sid, auth_token) 
            #Client object is created to place calls to the particlar account 
            call = client.calls.create(url='ngrokurl/flaskroutename',to=deets.tono,from_=deets.fromno) #places the call
            print(call.sid) #prints if successful

        elif sensor_value == 0:
            print("no burglar alert")
        print("checking btc value")
        percentage = 0.2*currentbtc
        instbtcprice = btcpricecheck()
        #calls the function and stores the returned value
        if instbtcprice > currentbtc:
            difference = instbtcprice - currentbtc
            if difference > percentage: 
              #checks if value increased by more than 20%
              print("the btc price: ",+str(instbtcprice))
              message = "Alert! its the right time to invest in BTC. The value has increased by " +str(difference)  
              #the alert text that's sent via telegram 
              telegram_status = send_telegram_message(message)                                #function called and status returned
              print("This is the Telegram status:", telegram_status)            
        elif instbtcprice <= currentbtc:
           print("btc price remains the same or has deccreased")
        print("PUSH BUTTON for 2 seconds if you need a weather check")
        time.sleep(2)   #delays time for 2 seconds after which value is fetched
        respbutton = mybolt.digitalRead(4)                                                #reads the value at GPIO pin 4 to check if its pushed
        databutton = json.loads(respbutton)                                               #returns response from button
        print(databutton)
        if databutton["success"] != 1:
            print("error with button output")
        if int(databutton["value"]) == 0:                                     #as there would be no potential difference between ground and pin when pushed
            weather_check(weatherr)
        elif int(databutton["value"]) != 0:
            print("please press button for 2 seconds if you need a weather check")

    except Exception as e: 
        print ("Error occured: Below are the details")
        print (e)
    time.sleep(10)                                                                       #repeats code after 10 seconds

Credits

Shivani Pothirajan

Shivani Pothirajan

1 project • 0 followers

Comments