We are making a industrial grade IoT device which can detect the temperature and then set boundaries for the temperature range. Then through the z score analysis detect if the temperature goes beyond the range and alert the user through the internet and messaging app called Twillio
STEPSSTEP 1: CONNECTIONS (See the LM35 from the flat side and left to right)
1. VCC pin of the LM35 connects to 5v of the Bolt Wifi module.
2. Output pin of the LM35 connects to A0 (Analog input pin) of the Bolt Wifi module.
3. Gnd pin of the LM35 connects to the Gnd.
STEP 2: SET UP THE CLOUD AND COLLECT AND PREDICT DATA POINTS
Now connect the bolt to laptop and log on to cloud.boltiot.com and note the ID of your Bolt WiFi Module.
After log in this will be the first page you will come across. Click on API tab in left bar
Now click on the API Tab and under the section for Generate Key, click on Enable.
And Voila! Your API is here (no you dont have to memorise it :P). Just copy it. You are good to go.
Now Create a product name "Temperature Detection". Make it Output device and make collection of data as GPIO
Then click on configure.
Click the radio button of A0 since we need analog values as output and name it temp variable. Then save it.
Click on code and write this code. This will help predict data points from your received temperature values and provide a range of the temperature.
setChartLibrary('google-chart');
setChartTitle('Polynomial Regression');
setChartType('predictionGraph');
setAxisName('time_stamp','temp');
mul(0.0977);
plotChart('time_stamp','temp');
Now save your settings and code. Link your device to cloud and keep the whole set up in refrigerator to collect the values of temperature for 2-3 hours.
After keeping the bolt module and temperature sensor in fridge for 2 hours
The predicted graph with temperature ranges
STEP 3: Z SCORE ANALYSIS AND ANOMALY DETECTION
CONFIGURATION FILENow we will create the SMS alert system:
STEP 1: Login into the putty(for windows) by entering the IP address of your digital ocean droplet. Put username as root and enter password
STEP 2: After login, create a file named conf.py which stores all the credentials related to Twilio and your bolt Iot module. To create a new folder with a file in it type in the terminal. After that
sudo mkdir anomaly
cd anomaly
sudo nano ano.py
After that write below code to save all the credentials..
SID = 'You can find SID 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 your Twilio Dashboard'
TO_NUMBER = 'This is your number. Make sure you are adding +91 in beginning
API_KEY = 'This is your Bolt Cloud accout API key'
DEVICE_ID = 'This is the ID of your Bolt device'
We store all the credentials (you have to replace with your own credentials) in a separate file since it is sensitive data and will be called by the main program on several occasions.
API & Device ID are your personal bolt IoT module credentials.
SID, FROM NUMBER & TOKEN are your personal Twilio credentials
TONUMBER is your personal mobile number
After replacing all the values, save the file using CTRL+X, press Y and then enter to exit the file.
MAIN PROGRAM - OBJECTIVE
- The code we execute has to perform Z-Score Analysis on the first Ten values taken by the temperature sensor
- This Z-values obtained consistently keep getting values and then try to predict the boundary values for the system
- The boundary values set by the algorithm then alert the user if any value goes beyond the ranges obtained
- On crossing these values, an alert is sent to the user. ( For this case, fridge is open)
- During the execution, if the temperature increases or decreases then it is considered as an anomaly and hence it is detected, thereby the system sends an alert on twillio and notify user.
import conf, json,time, requests, statistics, math
from boltiot import Sms, Bolt
def data_get(hdata, frame, factor):
if len(hdata)<frame :
return None
if len(hdata)>frame :
del hdata[0:len(hdata)-frame]
Mean = statistics.mean(hdata)
Variance= 0
for data in hdata :
Varianace= Variance + math.pow((data-Mean),2)
zn = factor * math.sqrt(Variance/frame)
hbound = hdata[frame-1]+zn
lbound = hdata[frame-1]-zn
return[hbound,lbound]
First we import all the library required to help us fulfill our objective.
- Then create a function date_get to obtain 10 values for the z score. If the data point are less we keep looping and if there are more we delete them.
- We calculate Mean, Variance and Z score.
- Then collecting all the values as hdata variable, we find the range of values.
mybolt = Bolt(conf.api, conf.id)
sms = Sms(conf.ssid, conf.token, conf.ton, conf.fromn)
hdata=[]
This help the main program call the configuration file and retrieve details and also twilio get the details from the configuration file. Then we declare hdata as an array to help store data in an index manner,
THE MAIN ALGORITHMwhile True:
response = mybolt.analogRead('A0')
data = json.loads(response)
if data['success'] != 1:
print("There was an error while retrieving the data.")
print("This is the error:" +data['value'])
time.sleep(10)
continue
print ("This temperature of your surrounding is "+data['value'])
sensor=0
try:
sensor = int(data['value'])
except Exception as e:
print("Error. Try again", e)
continue
This part basically helps you to fetch the data and if any error creeps in we throw an error and let the user know. We then set a variable sensor which will take in the integer values of the hdata values obtained.
NOTE data = json.loads(response)
If you print this statement then the output is {'value': '306', 'success': 1}
There fore to get only the integer values like 306 we have to implicitly convert it to int.
sensor = int(data['value'])
Proceeding to the next part of the program
bound = data_get(hdata, conf.frame, conf.factor)
if not bound :
reqbound= conf.frame -len(hdata)
print ("No. of points more needed are " , reqbound )
hdata.append(int (data['value']))
time.sleep(10)
continue
This is very simple to understand, Here we are counting how many points we have obtaine and how many more points do we need.
try :
temp = sensor/10.24
if temp > maxlimit:
print ("The Temperature value increased suddenly. Sending sms.")
print ("The Current temperature is: "+str(temp)+" °C")
response = sms.send_sms("Alert ! Someone has opened the fridge door")
print("This is the response ",response)
elif temp > minlimit or temp < maxlimit:
print("The fridge is cooling and tablet is safe")
print (" The Current temperature is:" +str(temp)+ "°C")
response = sms.send_sms("The fridge is cooling and tablet is safe")
print("This is the response",response)
history_data.append(sensor_value)
except Exception as e:
print ("Error",e)
time.sleep(10)
Here we are setting conditions when the fridge is cooling and when the fridge is being opened. Our minlimit and maxlimit are obtained through the STEP 2 Regression method and prediction graph.
Any error throws an exception and we can Proceed to debug!
OUTPUTThe final output of the whole project is in the following pictures. If all goes well, you will be ready with a product that can be used as a detect and alert system
I would like to THANK bolt IoT team for helping me learn a lot of technologies in such a short span. I wish to pursue more projects and keep building my knowledge!
Comments