In today's world, our life is fully dependent on the latest technology day by day. IoT has also made a contribution in making our lives easy. Contributing to this field, I have made an interesting project that will keep a real-time record of the temperature inside the refrigerator and will also notify via SMS when the door is opened using Z-score analysis for anomaly detection.
This technology can be used for smart refrigerators to avoid cooling loss inside them. This system can also be used in the industry to detect the abnormal temperature conditions and switching off the machines when overheated to prevent any damage and cooling them.
Hardware Connections:
- Take the LM35 sensor and connect the male to female wires on the legs of the sensor.
- Keeping flat side of sensor towards you, from left to right connect it to VCC(+5V), OUTPUT(A0) and GROUND(GND) of the BOLT IoT module.
- Using USB cable connect the module to a power source.
- Place it in the refrigerator preferably on the door to detect temp change.
Software setup:
Library Installation:
- Here I have used LINUX OS to make this project which will act as a cloud which will store the information received from Bolt module. Here I have used KALI LINUX (UBUNTU is preferred)
- Firstly, update the packages on the OS by the command below:-
sudo apt-get -y update
- Install python3-pip3, pip3 is a package manager for python3 which installs and manage packages and libraries:-
sudo apt install python3-pip
- Now, install boltiot library using pip:-
sudo pip3 install boltiot
Now we are done with boltiot library installation.
Twilio Configuration:
Twilio is a cloud communication platform as service (CPaaS) company which allows software developers to programmatically make and receive phone calls, text messages and perform other communication function using it's web service API's
Creating an account on Twilio
- Open https://www.twilio.com/ in browser.
- Click on Get a Free API Key button to sign up.
- Fill all the necessary details in SIGN UP form.
- To verify choose India as an option in the dropdown and then enter your phone number
- After verification you will be redirected to the dashboard and you will need to Create New Project.
- Click on "Products" and enable the SMS services by clicking on two checkboxes for Programmable SMS and Phone Numbers. Once you have done this, scroll to the bottom of the screen and click on "Continue".
- Now, you will need to give a name for your project. Click on "Continue" once we have entered the project name.
- Click on "Skip this step" when it asks to Invite a Teammate
- Our project should be created at this point. Click on "Project Info" to view the account credentials which is required for our projects
- You can view the Account SID and Auth token on this page. The Auth token is not visible by default, you can click on "view" button to make the Auth token visible as shown below. Copy both and save them somewhere securely.
- From the drop-down menu, choose "Programmable SMS". Now click on Get Started button to generate phone number
- Click on Get a number button. Then a popup will appear which will have the final number
- Click on Choose this number button to finalise this number.
GENERATING API IN BOLT CLOUD:
- Open cloud.boltiot.com and fill in your credentials.
- Go to device section, you will find the Device ID
- Go to API section, click on Manage API key and click on generate new API key.
CODING:
- Open the terminal in the LINUX OS.
- Make a new directory/folder named Anomaly_detect and enter it:-
mkdir Anomaly_detect
cd Anomaly_detect
- Create a configuration file which will store all the ID's, device name and phone numbers:-
sudo nano conf.py
When the editor is open type the following statements:-
SSID = 'You can find SSID in your Twilio Dashboard'
AUTH_TOKEN = 'You can find on your Twilio Dashboard'
FROM_NUMBER = 'This is the no. generated by Twilio. You can find this on Twilio Dashboard'
TO_NUMBER = 'This is your number. Make sure you are adding +91 in beginning'API_KEY = 'This is your Bolt Cloud account API key'
DEVICE_ID = 'This is the ID of your Bolt device'
FRAME_SIZE = 3
MUL_FACTOR = 6
Don't forget to replace the above values with your credentials!!
I have set FRAME_SIZE to 3 and MUL_FACTOR to 6 so that it consider previous 3 readings to calculate anomaly which will increase the accuracy. Press 'CTRL+X' to save the file.
- Create one more file named anomaly_detection.py using following command:-
sudo nano anomaly_detection.py
This file will contain the main code. The algorithm for the code can be broken down into the following steps:
1) Fetch the latest sensor value from the Bolt device.
2) Store the sensor value in a list, that will be used for computing z-score.
3) Compute the z-score and upper and lower threshold bounds for normal and anomalous readings.
4) Check if the sensor reading is within the range for normal readings.
5) If it is not in range, send the SMS.
6) Wait for 5 seconds.
7) Repeat from step 1.
- Firstly import the libraries to be used while coding:-
import conf, json, time, math, statistics
from boltiot import Sms, Bolt
The math and statistics libraries will be required for calculating the Z-score and the threshold boundaries.
The following lies code helps define a function which calculates the Z-score and the using the Z-score calculates the boundaries required for anomaly detection.
def compute_bounds(history_data,frame_size,factor):
The above line helps define a function, which takes 3 input variables: hisotry_data, frame_size and factor.
if len(history_data)<frame_size :
return None
if len(history_data)>frame_size :
del history_data[0:len(history_data)-frame_size]
The above code checks whether enough data has been accumulated to calculate the Z-score, and if there is too much data, then the code deletes the older data.
Mn=statistics.mean(history_data)
The above code calculates the mean (Mn) value of the collected data points.
Variance=0
for data in history_data :
Variance += math.pow((data-Mn),2)
This code helps to calculate the Variance of the data points.
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]
Here we calculate the Z score (Zn) for the data and use it to calculate the upper and lower threshold bounds required to check if a new data point is normal or anomalous. The formulas to calculate Z Score are:-
The next code is used to initialize the Bolt and SMS variables, which we will use to collect data and send SMS alerts. Here we also initialize an empty list with the name 'history_data' which we will use to store older data, so that we can calculate the Z-score.
mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
sms = Sms(conf.SSID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)
history_data=[]
The following while loop contains the code required to run the algorithm of anomaly detection.
while True:
response = mybolt.analogRead('A0')
data = json.loads(response)
if data['success'] != 1:
print("There was an error while retriving the data.")
print("This is the error:"+data['value'])
time.sleep(5)
continue
sensor_value1 = int(data['value'])
sensor_value1 = sensor_value1/10.24
print ("The current Temparature of your Refrigarator is "+ str(sensor_value1)+" degree celsious. And the Sensor Value is "+data['value'])
sensor_value=0
try:
sensor_value = int(data['value'])
except e:
print("There was an error while parsing the response: ",e)
continue
bound = compute_bounds(history_data,conf.FRAME_SIZE,conf.MUL_FACTOR)
if not bound:
required_data_count=conf.FRAME_SIZE-len(history_data)
print("Not enough data to compute Z-score. Need ",required_data_count," more data points")
history_data.append(int(data['value']))
time.sleep(5)
continue
try:
if sensor_value > bound[0] :
sensor_value1 = sensor_value/10.24
print ("The Temparature level has been INCREASED suddenly.Sending SMS")
response = sms.send_sms("Someone Opened the fridge door. The Current temperature is " + str(sensor_value1)+ " degree celsious")
print("This is the response for SMS ",response)
history_data.append(sensor_value);
except Exception as e:
print ("Error",e)
time.sleep(5)
Therefore, combining the above parts, here is the full code:-
import conf, json, time, math, statistics
from boltiot import Sms, Bolt
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]
mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
sms = Sms(conf.SSID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)
history_data=[]
while True:
response = mybolt.analogRead('A0')
data = json.loads(response)
if data['success'] != 1:
print("There was an error while retriving the data.")
print("This is the error:"+data['value'])
time.sleep(5)
continue
sensor_value1 = int(data['value'])
sensor_value1 = sensor_value1/10.24
print ("The current Temparature of your Refrigarator is "+ str(sensor_value1)+" degree celsious. And the Sensor Value is "+data['value'])
sensor_value=0
try:
sensor_value = int(data['value'])
except e:
print("There was an error while parsing the response: ",e)
continue
bound = compute_bounds(history_data,conf.FRAME_SIZE,conf.MUL_FACTOR)
if not bound:
required_data_count=conf.FRAME_SIZE-len(history_data)
print("Not enough data to compute Z-score. Need ",required_data_count," more data points")
history_data.append(int(data['value']))
time.sleep(5)
continue
try:
if sensor_value > bound[0] :
sensor_value1 = sensor_value/10.24
print ("The Temparature level has been INCREASED suddenly.Sending SMS")
response = sms.send_sms("Someone Opened the fridge door. The Current temperature is " + str(sensor_value1)+ " degree celsious")
print("This is the response for SMS ",response)
history_data.append(sensor_value);
except Exception as e:
print ("Error",e)
time.sleep(5)
PROJECT OUTPUT:
As we have written the code for detecting the anomaly, lets run the code. To run it give the command:
sudo python anomaly_detection.py
After 15 sec (5 sec delay with frame size 3) system will start printing the values.
After we open the fridge, immediately the temperature rises, and it will print out that "The temperature level has been increased suddenly. Sending SMS" and it will also print the degree celsius as well as the sensor value.
Comments