Temperature plays a major role in today's world, even a minute change in temperature at industries may cause explosions which leads to disasters and loss of precious life of humans. To protect people from these disasters we have designed this project which alerts the people by sending emails, messages and tweets when temperature crosses threshold value or if any anomaly is detected.
Through these tweets the person can remind the workers about the temperature crossing threshold value, then there is a chance of taking preventive measures to stop disasters at various industries like pharmaceutical companies, etc...
In pharmaceutical companies certain temperature must be maintained, if temperature exceeds then the medicine created at that time can't beour product used for medication because they may be harmful if used for medication as temperature was not consistent, leading to a great loss for the company. Our product will also be helpful to reduce these type of losses.
STEPS TO BUILD THE PROJECT
Step 1. Hardware ComponentsWe need the following components to build the whole project:
i. Bolt WiFi module
ii. LM35 Temperature sensor
iii. 3 Jumper wires ( Male to Female )
iv. Micro-USB cable ( mobile charger can also be used )
v. Power Source ( power bank can also be used )
Step 2. Hardware Configuration- Bolt Wifi module is connected to LM35 temperature sensor through jumper wires.
- Using male to female wire we will connect the 3 pins of the LM35 to the Bolt Wifi Module as follows:
- Connect VCC pin of the LM35 to 5v of the Bolt Wifi module.
- connect Output pin of the LM35 to A0 (Analog input pin) of the Bolt Wifi module.
- connect GND pin of the LM35 to the GND.
First, we need to create a digital ocean account. Please click here (https://m.do.co/c/679338b50344) and create a new account. Type email id and password for Signing up and we will receive an account verification email. Open the email and click on the link to confirm our account.
After confirming your account, we need to add billing.
In this step, we will choose the appropriate image(version and type of OS) of droplet for this training. First, click on Create button and choose Droplet from the drop-down menu and the 'Create droplet' screen will appear. At the time of this writing, the 64-bit Ubuntu 18.10 image is selected by default and we will use the same version for this training
In this step we will choose the size of the droplet i.e. the amount of RAM and storage space it should have.
Datacenter region is the place where our droplet will be deployed. It's like someone has bought a computer for you in that place. For the best performance, choose the data center nearest to us and our users. More distant server locations may increase the server's latency without providing any practical benefits. I am from India, so I kept Bangalore as the default datacenter region
Once we have selected our options, click Create.
after creating droplet, we will receive a mail where we will get our ip address and login password.
We created a droplet and got the login credentials and server IP over emails. Now, we will learn about tools/software for ssh(login to the server) into our server. for windows os we can use putty to write the code and to execute. for mac we will use the terminal for writing as well as running the code.
We will login through terminal to Digital ocean server.
Then type password and press enter. Password won’t be visible and we will have to type the same password for the first time, which is mailed to us from DigitalOcean.
After this, we are asked to change our password and we need to type our current password. And then we are asked to enter our new password twice for confirmation. Keep this password somewhere safe, because next time we have to type this new password.
The Bolt Python library makes it easy to interact with the Bolt cloud API from our Python application.
We can control or fetch the data from Bolt cloud to our server(Here Ubuntu from DigitalOcean ), Bolt Python library will help us in building the IoT product.
Before we proceed to this step, first ssh(login) to Ubuntu server and follow the below steps to use Bolt Python library in code.
4a. Update the packages on UbuntuExecute the command below so that the packages on Ubuntu are updated to the latest version.
sudo apt-get -y update
4b. Install python3 pip3pip3 is a package manager for python3 used to install and manage packages and python libraries. It is system independent.
Install pip3 using the following command,
sudo apt install python3-pip
4c. Installing boltiot Library Using pipNow we will install the boltiot python library on your Ubuntu server.
Type the below command in terminal to install boltiot python library.
sudo pip3 install boltiot
Now we are done with bolt iot python library installation.
Step 5. Twilio ConfigurationSMS Configuration -Twilio is a third-party SMS functionality provider. It is a cloud communications platform as a service (PaaS) company. Twilio allows software developers to programmatically make and receive phone calls and also send and receive text messages using its web service APIs.
Creating an account on Twilio
a. Open https://www.twilio.com/ in browser.
b. Click on Get a Free API Key button to sign up.
c. Fill all the necessary details in SIGN UP form. Below is the screenshot of filled sign up form.
d. To verify they will ask for our phone number. Choose India as an option in the dropdown and then enter our phone number
e. After verification we will redirect to our dashboard and we will need to Create New Project.
f. Click on "Products" as shown on the screen below, and enable the SMS services by clicking on two checkboxes for Programmable SMS and Phone Numbers as shown below. Once you have done this, scroll to the bottom of the screen and click on "Continue".
g. Now, we will need to give a name for our project. I have given the name as My Project. Click on "Continue" once we have entered the project name.
h. Click on "Skip this step" when it asks to Invite a Teammate
i. Our project should be created at this point. Click on "Project Info" to view the account credentials which is required for our projects
j. We can view the Account SID and Auth token on this page. The Auth token is not visible by default, we can click on "view" button to make the Auth token visible as shown below. Copy both and save them somewhere securely.
k. From the drop-down menu, choose "Programmable SMS". Now click on Get Started button to generate phone number
l. Click on Get a number button. Then a popup will appear which will have the final number
m. Click on Choose this number button to finalise this number.
n. By this method we can generate several numbers and we can see these numbers in Active Numbers area
o. To check whether this is working or not, we have to go to Build with Programmable SMS and send a message to our given phone number. if everything is ok then it ill work, but if message has not received, then we have to again set up from beginning.
Mailgun is an Email automation service. It has a very powerful set of inbuilt functions for sending emails. Developers can process their email with the help of Mailgun API
Creating an account on Mailgun
a. Open https://www.mailgun.com/ in browser.
b. Click on Sign Up button.
c. Fill all the necessary details in SIGN UP form. Below is the screenshot of filled sign up form.
d. We will get a verification mail having a link. Click on that link to verify our mail.
e. To verify they will ask for phone number. Choose India as an option in the dropdown and then enter our phone number.
f. After verification, we will go to domain and click on sandbox url
g. Now we need to verify our mail address to receive mail from mailgun. for this we need to enter our mail address in authorised recipient section. we will receive the mail then we have to verify our email address.
Mailgun Mail Address Verify
h. We need to click on API section for API key and API url.
Mailgun API Key
Step 7. Generating API in Bolt Cloud7a. Device IDwe can find the device id under device section.
BOLT Device ID
7b. API KeyWe have to generate Bolt API key as the following in Bolt cloud:
BOLT API Key
Step 8. Coding :1. Make the same circuit connections as described before.
2. Once you are done with that, log in to digitalOcean droplet and create a new folder to hold the files for this topic.
3. We can create a new folder and enter it using the following command.
mkdir Anomaly_Detectioncd Anomaly_Detection
4. Create a configurations file for this project, using the following command.
sudo nano conf.py
After the editor is open, type in the following configuration parameters
#You can find SSID in your Twilio Dashboard
SSID = 'AC7ae69b9370XXXXXXXXXX6978d3ce4ce8'
#You can find AUTH TOKEN on your Twilio Dashboard
AUTH_TOKEN = 'eb4563dfdXXXXXXXXXXadde03ae817bb'
#FROM_NUMBER,This is the no. generated by Twilio.
FROM_NUMBER = '+16XXXXXXX80'
#TO_NUMBER,This is your number
TO_NUMBER = '+91XXXXXXXX03'
#This is the private API key which you can find on your Mailgun Dashboard
MAILGUN_API_KEY = '4beed33869c0a7de8b97XXXXXXXXXXXX-060550c6-e591c150'
#SANDBOX_URL,You can find this on your Mailgun Dashboard
SANDBOX_URL= 'sandbox12b9e8227bf34c118XXXXXXXXXXXXXXX.mailgun.org'
#SENDER_EMAIL,This would be test@your SANDBOX_URL
SENDER_EMAIL = 'test@sandboxXXXXXXXXXXXXXXX18ccec4718337b3f6.mailgun.org'
#RECIPIENT_EMAIL,Enter your Email ID Here
RECIPIENT_EMAIL = 'cbXXXXXX@gmail.com'
#API_KEY,This is your Bolt Cloud account API key
API_KEY = '499d00d0-81f6-XXXX-XXXX-7caaecca6e93'
#DEVICE_ID,This is the ID of your Bolt device
DEVICE_ID = 'BOLTXXXXXXX6'FRAME_SIZE = 10
MUL_FACTOR = 6
Note: We have to replace all the above value with our credentials. We can find the first four values in Twiliodashboard and the last two in Bolt Cloud dashboard.
You can set the FRAME_SIZE to 10, and the MUL_FACTOR to 6 for now. Once done, we can save the configurations file by pressing 'CTRL+x'
5. Now create one more file named anomaly_detection.py, using the 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:
5.1) Fetch the latest sensor value from the Bolt device.
5.2) Store the sensor value in a list, that will be used for computing z-score.
5.3) Compute the z-score and upper and lower threshold bounds for normal and anomalous readings.
5.4) Check if the sensor reading is within the range for normal readings.
5.5) If it is not in range, send the SMS.
5.6) Wait for 10 seconds.
5.7) Repeat from step 5.1.
6. Here we will start writing the code. Let us start with the imports.
import conf, json, time, math, statisticsfrom boltiot import Sms, Bolt, Email
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. You can read more about variance here.
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 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)
mailer = Email(conf.MAILGUN_API_KEY, conf.SANDBOX_URL, conf.SENDER_EMAIL, conf.RECIPIENT_EMAIL)history_data=[]
The following while loop contains the code required to run the algorithm of anomaly detection.
while True:
response = mybolt.analogRead('A0')
response1 = mybolt.analogRead('A0')
response2 = 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")
response1 = mailer.send_email("RED Alert", "Someone opened the fridge door. Because The Temparature of your Refrigarator has been INCREASED suddenly. The Current temperature is " + str(sensor_value1)+" degree celsious")
response2 = sms_whatsapp.send_sms("Someone opened the fridge door. Because The Temparature of your Refrigarator has been INCREASED suddenly. The Current temperature sensor value is " + str(sensor_value1)+ " degree celsious")
print("This is the response for SMS ",response)
print("This is the response for EMAIL ",response1)
print("This is the response for WHATSAPP ",response2)
history_data.append(sensor_value);
except Exception as e:
print ("Error",e)
time.sleep(5)
Here is the full code in one frame
import conf, json, time, math, statistics
from boltiot import Sms, Bolt, Email
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)
mailer = Email(conf.MAILGUN_API_KEY, conf.SANDBOX_URL, conf.SENDER_EMAIL, conf.RECIPIENT_EMAIL)history_data=[]
while True:
response = mybolt.analogRead('A0')
response1 = mybolt.analogRead('A0')
response2 = 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")
response1 = mailer.send_email("RED Alert", "Someone opened the fridge door. Because The Temparature of your Refrigarator has been INCREASED suddenly. The Current temperature is " + str(sensor_value1)+" degree celsious")
response2 = sms_whatsapp.send_sms("Someone opened the fridge door. Because The Temparature of your Refrigarator has been INCREASED suddenly. The Current temperature sensor value is " + str(sensor_value1)+ " degree celsious")
print("This is the response for SMS ",response)
print("This is the response for EMAIL ",response1)
print("This is the response for WHATSAPP ",response2)
history_data.append(sensor_value);
except Exception as e:
print ("Error",e)
time.sleep(5)
Step 9. Project Output and How it Works :Now that we have written the code for anomaly detection lets run the code.Once that is done, run the anomaly detection code using the following command
sudo python3 anomaly_detection.py
After about 100 seconds (10 seconds delay with a frame size of 10), the system will start printing the values, as per the following image
Temperature Monitoring
Note: If you are not getting these results, try changing the FRAME_SIZE and MUL_FACTOR values in the conf.py file.
After we open the fridge, immediately the temperature rises, and it will print out that "The temperature level hasbeen increased suddenly. Sending SMS" and it will also print the degree celsius as well as the sensor value.
Anomaly Detected
An Email, and SMS will also be received that time stating the anomaly.
eg:someone opened the refrigerator.
This is the complete project. Thanks everyone!
Comments