Rishabh Prabhat Saxena
Published

Temperature anomaly detection system

Continuously reads the temperature and raises alert if the anomaly is found. It also turns on the buzzer if anomaly continues

IntermediateFull instructions provided340
Temperature anomaly detection system

Things used in this project

Hardware components

Bolt WiFi Module
Bolt IoT Bolt WiFi Module
×1
USB-A to Mini-USB Cable
USB-A to Mini-USB Cable
×1
Temperature Sensor
Temperature Sensor
×1
Buzzer
Buzzer
×1
Breadboard (generic)
Breadboard (generic)
×1
copper wires
×1

Software apps and online services

Bolt Cloud
Bolt IoT Bolt Cloud
Bolt IoT Android App
Bolt IoT Android App
SMS Messaging API
Twilio SMS Messaging API
MailGun
Telegram
Oracle VM VirtualBox

Story

Read more

Schematics

Circuit Connections

Code

conf

Python
This file contains all the API keys and URLs which are necessary for sending alerts.
api_key='XXXXXXXXXXXXXXXXX'
dev_id='BOLTXXXXXXXXXX'
#Twilio

sid='XXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token='XXXXXXXXXXXXXXXXX'
from_no='+XXXXXXXXXX'
to_no='+XXXXXXXXX'

#Mailgun

mailgun_api='XXXXXXXXXXXXXXXXX'
sandbox_url='sandboxeXXXXXXXXXXXXXXXXXXXX.mailgun.org'
sender_email='test@'+sandbox_url
recipient_email='XXXXXXXXXXXXXX@XXXXXXXXXXXXXX.XXXXX'

#telegram

tele_chat_id='@XXXXXXXXXXXXXXXXX'
tele_bot_id='botXXXXXXXXXXXXXXXXXXXXXXXXX'

TempDetect

Python
import conf,json,time,math,statistics,requests
from boltiot import Bolt,Sms,Email

#collecring data from LM35 sensor

mybolt=Bolt(conf.api_key,conf.dev_id)
def fetch_data():
    try:
        print("\nTrying to fetch data")
        response=mybolt.analogRead('A0')
        data=json.loads(response)
        if data['success']!=1:
            print('Request failed and response is: '+str(data))
            return None
        sensor_val=int(data['value'])*100/1024
        return sensor_val

    except Exception as e:
        print(e)
        return None


#computing bound to detect anomaly
his_data=[]
frame_size=10
factor=1.7


def bounds(his_data,frame_size,factor):
    if len(his_data) < frame_size:
        print('Data insufficient...\n{} more data required'.format(frame_size-len(his_data)))
        return None

    if len(his_data) > frame_size:
        del his_data[0:len(his_data)-frame_size]

    val = his_data[-1]
    Mn = statistics.mean(his_data)
    Var = 0
    for data in his_data:
        Var = Var+math.pow((data-Mn), 2)
    Z = factor*math.sqrt(Var/frame_size)
    high_bound=val+Z
    low_bound=val-Z
    print('High Bound is {} and low Bound is {}'.format(high_bound, low_bound))
    print('range is: '+str(high_bound-low_bound))
    return [high_bound, low_bound]



#Detecting anomaly

anomaly_count=0


def detect_anomaly(temp,bound):
    global anomaly_count
    if temp > bound[0] or temp < bound[1]:
        anomaly_count=anomaly_count+1
        print('anomaly detected '+str(anomaly_count))
        return True

    else:
        anomaly_count=0
        return False


#Send telegram message

def send_telegram(message):
    print('Trying to send telegram message.....')
    url='https://api.telegram.org/'+conf.tele_bot_id+'/sendMessage'
    data={'chat_id':conf.tele_chat_id,'text':message}
    try:
        response=requests.request('POST',url,params=data)
        print('sending alert through Telegram')
        print('response from Telegram: '+response.text)
    except Exception as e:
        print(e)

    return json.loads(response.text)['ok']


#sending sms through Twilio

def send_sms_twilio(message):
    sms=Sms(conf.sid,conf.auth_token,conf.to_no,conf.from_no)
    try:
        print('Trying to send SMS')
        response=sms.send_sms(message)
        print('response from the twilio is: '+str(response))
        print('status of sms is: '+str(response.status))
    except Exception as e:
        print('exception occured: \n'+e)



#sending mail through mailgun

def send_email_mailgun(message):
    mailer=Email(conf.mailgun_api,conf.sandbox_url,conf.sender_email,conf.recipient_email)
    try:
        print('Trying to send email')
        response=mailer.send_email('URGENT: Refrigeration Issue',message)
        print('response received from the mailgun is: '+str(json.loads(response.text)['message']))
    except Exception as e:
        print(e)


# main loop

bound=[]
result_anomaly=False

while True:
    try:
        temp=fetch_data()
        print('Current Temprature is: '+str(temp))
        if temp!=None:
            his_data.append(temp)
        if bound:
            result_anomaly=detect_anomaly(temp,bound)
        bound=bounds(his_data,frame_size,factor)
        if bound==None:
            print('Please Wait.....')
            time.sleep(10)
            continue
        if result_anomaly==True:
            message='An anomaly is detected in the functioning of your Refrigerator. Current temprature is '+ str(temp)
            send_telegram(message)
            if anomaly_count > 2:
                critical_message=message+'\nANOMALY IS DETECTED MORE THAN 2 TIMES.\nHence the alarm is raised automatically.\n Press the "BUZZER OFF" button through Bolt app to stop the Buzzer'
                send_sms_twilio(critical_message)
                send_email_mailgun(critical_message)
                res=mybolt.digitalWrite('1','HIGH')
                print(str(json.loads(res)))
    except Exception as e:
        print(e)

    time.sleep(10)

Buzzer

HTML
This file controls the buzzer
<!DOCTYPE html>
<html>
    <head>
        <title>Buzzer</title>
        <script type="text/javascript" src="https://cloud.boltiot.com/static/js/boltCommands.js"></script>
       <script>
       setKey('{{ApiKey}}','{{Name}}');
       </script>
       <style>
.button1 {
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  padding: 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 50%;
  top: 50%;
  left: 50%;
   margin: 0;
  position: absolute
  transform: translate(-50%, -50%);
  }
  </style>
   </head>
   <body>
       <center>
        <div style="height: 50px;">If your device shows the anomalous behavior more than 2 times</div>
        <div style="height: 50px;">then the buzzer will automatically turns on,</div>
        <div style="height: 50px;">to switch it off press the following</div>
        <div style="height: 50px;">'BUZZER OFF' button</div>
        <div style="height: 150px;">
       <button class="button1" onclick="digitalWrite('1','LOW');">BUZZER OFF</button>
       </div>
       </center>
   </body>
   

Credits

Rishabh Prabhat Saxena

Rishabh Prabhat Saxena

1 project • 1 follower

Comments