Priyam Srivastava
Published © GPL3+

Easy guide to Build your Light Detector Friend!!

Heo! If you have just started to peep into IOT or if looking to build your first IOT project or one with curiosity. CHECK OUT HOW EASY IT IS.

IntermediateFull instructions provided2 hours282
Easy guide to Build your Light Detector Friend!!

Things used in this project

Hardware components

Bolt WiFi Module
Bolt IoT Bolt WiFi Module
×1
LDR, 5 Mohm
LDR, 5 Mohm
×1
Resistor 10k ohm
Resistor 10k ohm
×1
Test Accessory, Power Supply Adapter
Test Accessory, Power Supply Adapter
×1

Software apps and online services

Bolt Cloud
Bolt IoT Bolt Cloud
Bolt IoT Android App
Bolt IoT Android App
Ubuntu OS
VMware

Story

Read more

Code

Light_detector_alert

Python
The file contains two parts and each part consists of codes of a different python files

Part 1 - Line 1 to Line 23
File conf.py ------> Information regarding api_key and device_id and Mailgun credentials etc. Line 1
to Line 23 of code.

Part 2 Line 29 to the End of code
File light_detector.py -----> Code for accessing the value from bolt device and sensor and computing
Z-score to detect and anomaly in order to Alert a User if any Anomaly occurs.
######################### Content of Configuration file conf.py #########################



            ######### find these two on your Mailgun Dashboard ########
          
MAILGUN_API_KEY = "6c9ed9e4XXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXX-XXXXXXXX"
SANDBOX_URL= 'sandbox178XXXXXXXXXXXXXXXXXXXXX.mailgun.org' 
         
            ###########################################################                        
SENDER_EMAIL = 'test@_Your_SANDBOX_URL----> mentioned above"              
RECIPIENT_EMAIL = 'Enter your Email ID Here'

            ########## find these on your Bolt cloud account ###########

API_KEY = 'This is your Bolt Cloud account API key'
DEVICE_ID = 'This is the ID of your Bolt device'

            ################# initializing Prequisites #################


FRAME_SIZE = 10          # No of data_counts required to calculate Z-score
MUL_FACTOR = 6           # Factor that determine the width of anomaly detetcion boundary

################################# END OF conf.py FILE ###################################


######################## Content of main file light_detector.py #########################


import conf, json, time, math, statistics    # Here conf is the file with above contents
from boltiot import Email, Bolt


########################## Defining Compute_bounds() function ###########################

def compute_bounds(history_data,frame_size,factor):
  
  if len(history_data)<frame_size :
    return None
  if len(history_data)>frame_size :
    del history_data[0:len(history_data)-frame_size]
  
  Mn=statistics.mean(history_data)
  
  Variance=0
    for data in history_data :
        Variance += math.pow((data-Mn),2)
  
  Zn = factor * math.sqrt(Variance / frame_size)
  High_bound = history_data[frame_size-1]+Zn
  Low_bound = history_data[frame_size-1]-Zn
  
  return [High_bound,Low_bound]

############################### INITIALIZING PREQUISITES ################################

mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
mailer = Email(conf.MAILGUN_API_KEY, conf.SANDBOX_URL, conf.SENDER_EMAIL, conf.RECIPIENT_EMAIL)
history_data=[]  # empty list to store previous values

#########################################################################################


while True:
  
  response = mybolt.analogRead('A0')
  data = json.loads(response)
  
  ######### Checking if data is retrieved successfully ##########
  
  if data['success']!=1:
    
    print("There was an error while retrieving data.")
    print("This is th error"+str(data['value']))
    time.sleep(10)
    continue
  
  ###############################################################
  
  print("This is the value "+str(data['value']))
  
  sensor_value = int(data['value']) 
  
  ################## Calling Compute_bound() function ###################
  
  bound = compute_bounds(history_data, conf.FRAME_SIZE, conf.MUL_FACTOR)
  
  ####### Checking if enough no of data_counts to compute Z-score #######
  
  if not bound:
    
    requierd_data_count = conf.FRAME_SIZE-len(history_data)
    print("Not enough data_counts to compute Z-score. Need ",required_data_coumt,"more!")
    history_data.append(sensor_value)
    time.sleep(10)
    continue
  
  ############### Code for Anomaly Detection & EMAIL ALERT!! ###############
  
  try:
    
    if sensor_value > bound[0] or sensor_value < bound[1]:
      
      print("Making a request to Mailgun to send Email Alert!")
      response      = mailer.send_email("Alert!", "Someone messed up with the Lights!")
      response_text = json.loads(response.text)
      print("Response received from Mailgun is "+str(response_text['message']))
  
  
  except Exception as e:
    
    print("There was an error", e)
    
  ##########################################################################
  
  time.sleep(10)
  
  ####################################### THE END #######################################

Credits

Priyam Srivastava

Priyam Srivastava

1 project • 1 follower
Thanks to Bolt Training course and Pranav Pai Vernekar.

Comments