Throughout the human history there have been many instances of industrial fires.In the early times when there was no technology to monitor a complex system, man was the only option to do it. Therefore any subtle changes could not be analyzed beforehand. Hence it was very difficult to prevent a mishap.But now due to advancements in technology there is a way to know about an anomaly and to prevent any mishap.Introduction -
Capstone Project - Temperature Alertinator
Language used – Python (MachineLearning)
This project deals with constantly monitoring the temperature using LM35 and Bolt IoT WiFi Module. Any deviation from the given temperature range will be detected by module and the user will be notified by a mail sent using Mailgun services.Polynomial Regression is used to predict future values along with Z-score analysis which help to constantly plot a graph of the ongoing things and hence any anomaly will be caught and the user will know about it by an SMS using Twilio services.Steps -A. Connect the LM35 and the Bolt Iot's WiFi module.
Step 1: Hold the sensor in a manner such that you can read LM35 written on it.
Step 2: In this position, identify the pins of the sensor as VCC, Output and Gnd from your left to right.
In the above image, VCC is connected to the blue wire, Output is connected to the green wire and Gnd is connected to the yellow wire. Step 3: Using male to female wire connect the 3 pins of the LM35 to the Bolt Wifi Module as follows:
- VCC pin of the LM35 connects to 5v of the Bolt Wifi module.
- Output pin of the LM35 connects to A0 (Analog input pin) of the Bolt Wifi module.
- Gnd pin of the LM35 connects to the Gnd.
Create a new project on Bolt cloud and link it to your device.
Below is the image to link your device and module.
Name your project and select the above shown data.C. Setup for the product
On the Bolt Cloud in the setup section choose the pins of your module to be used and write the code for the project.
Save the configuration and exit.D. Let the module rest for about 2 hours and see the output.
Keep the module in the refrigerator and check the output after about 2hours.
Above is the graph for the temperature range of my fridge.
Maximum limit =11.71 (i.e. sensor value 120) Minimum limit =9.27 (i.e. sensor value 95)E. Write a python code
NOTE - CREATE AN ACCOUNT ON MAILGUN AND TWILIO BECAUSE YOU WILL NEED YOUR CREDENTIALS IN YOUR CODE.REFER THE BOLT TRAINING TO DO SO.
In the terminal make a new directory using the commands shown below
mkdir Anomaly_Detection; cd Capstone_Project
Now create a file named email_conf.py to store all your Mailgun credentials.To do so type the following on your terminal
sudo nano email_conf.py
This is how your file will look. Enter the details.
Save the file using ctrl+x.
Similarly create a new file named sms_conf.py to store all your Twilio credentials.To do so type the following on your terminal
sudo nano sms_conf.py
This is how your file will look. Enter the details.
Save the file using ctrl+x.
Now create one more file named capstone_project.py, using the following command
sudo nano capstone_project.py
This file will carry the actual code of your project;.
Algorithm of the code:
1) Fetch the sensor value at the given instance 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 along with upper and lower threshold bounds for normal and anomalous readings.
4) Check if the sensor reading is within the range for normal readings. i.e. no sudden increase in temperature
5) If it is not in range, send the mail.
6) Check if the sensor value is in the range specified in our min and max values.
7) If it is not in range, send the SMS.
8) Wait for 10 seconds.
9) Repeat from step 1.
- First import the ( sms_conf.py & email_conf.py ) files which have all the credentials, json and time.
- Also we import our Bolt python library which will let us fetch the data stored in Bolt Cloud and then based on value send Email and SMS.
- The math and statistics libraries will be required for calculating the Z-score and the threshold boundaries.
import sms_conf,email_conf, json, time, math, statistics from boltiot import Sms, Email, Bolt
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.
Now we will initialize two variables which will store minimum and maximum threshold value. You can initialize any minimum and maximum integer limits to them.
This would send an alert if the temperature reading goes below the minimum limit or goes above the maximum limit.
minimum_limit =95 maximum_limit =120
mybolt = Bolt(email_conf.API_KEY, email_conf.DEVICE_ID)
The above code will automatically fetch your API key and Device ID that you have initialized in
mailer = Email(email_conf.MAILGUN_API_KEY, email_conf.SANDBOX_URL, email_conf.SENDER_EMAIL, email_conf.RECIPIENT_EMAIL)
The above code will automatically fetch your MAILGUN_API_KEY, SANDBOX_URL, SENDER_EMAIL and RECIPIENT_EMAIL that you have initialized in
email_conf.py file. Make sure you have entered the correct values in
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.
sms = Sms(conf.SSID,conf.AUTH_TOKEN,conf.TO_NUMBER,conf.FROM_NUMBER) history_data=
The given while loop consists 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(10) continue print ("This is the value "+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,email_conf.FRAME_SIZE,email_conf.MUL_FACTOR) if not bound: required_data_count=email_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(10) continue print("bound",bound) print("bound",bound) try: if sensor_value > bound : print ("The Temperature increased suddenly. Sending a sms through Twilio.") print ( "The Current temperature is: "+str(sensor_value) ) response = sms.send_sms("Alert! Someone has opened the fridge door") print("Response :",response) elif sensor_value > maximum_limit or sensor_value < minimum_limit: print("Alert! The temperature condition can destroy the tablets. Sending an email through Mailgun.") print ("The Current temperature is:" +str(sensor_value)) response = mailer.send_email("Alert!","The current temperature can destroy the tablets.") print("Response:",response) history_data.append(sensor_value); except Exception as e: print ("Error occured:Below are the details") print(e) time.sleep(10)
Below are the screen shots of the code:
Write the following command to run your code
sudo python3 capstone_project.py
Below are the pictures of the output
By seeing the output you know that if the temperature goes out of the given range then Mailgun will send you a mail.Also if there is a sudden change in the temperature then you have a SMS from Twilio notifying about the same.
For any queries visit the bolt forum.