This project is basically a temperature alert system and this project will send alert when there is any temperature breach or when our system crosses threshold values of temperature. Here IoT platform of Bolt is used to take the temperature reading from the wifi module sensor as input and Machine Learning is used to find the anomaly of the temperature using the z-score analysis.
1. In Pharmaceutical companies.
2. In food storage of factories.
3. In server rooms.
and all such places where specific temperature range is required.
Video Link:The video completely explain the functioning as well as the output of the project.
STEPS:1. Hardware Connection-First of all hold the sensor in a manner such that you can read LM35 written on it.
Now, In this position, identify the pins of the sensor as VCC, Output and Gnd from your left to right.
VCC pin plugged in 5v point of wifi module (black wire)
Output pin plugged in 'A0' point of wifi module(white wire)
Gnd pin plugged in 'gnd' point of wifi module(grey wire)
Step1. Create a new product on bolt cloud named as 'temp_alert'
Step2. Do Hardware configuration as shown in image below and take the variable as 'temp'.
Step3. Now write the code in "Code" portion. During configuring we write this code for taking polynomial regression in action an then we linked the device.
setChartLibrary('google-chart');
setChartTitle('Temp Prediction and Anomaly Detection');
setChartType('predictionGraph');
setAxisName('time_stamp','temp');
mul(0.0977);
plotChart('time_stamp','temp');
Save the code and exits.
Later link the product to the bolt module and deploy the configuration.
Step4. Let the module rest for about 2 hours and see the output.
After almost 2 hours we get the graph,
It has three colored lines-
The Blue line shows us the Actual value sensed by sensor.
The red line shows the predicted history.
The orange line shows us the predicted temperature for the next slot of times.
First of all create account on [ refer to BoltIoT training for the detailed procedure]
1. Digital Ocean Server and make your own private server and use 'puTTY'.
puTTY is a free Telnet and SSH terminal software for Windows and Unix platforms that enable users to remotely access computers over the Internet.
Note: If you are using VirtualBox or VMWare or a Linux system, log in to the system accordingly.
2. Twilio (for SMS alert service)
3. Mailgun (for alert through gmail)
4. Telegram and add bot into your channel.
A. ConfigurationNow we open the puTTY app to sign in our Digital ocean server by IP address provided by digital ocean.
Now, sign in as "root" as your username and your password.
1. Create a file name conf.py
for saving all your credentials which you will use in further coding for security purpose and to avoid data leakage.
sudo nano conf.py
2. Now add all your credentials in conf.py
folder
""" TWILIO CONFIGURATION """
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 Twilio Dashboard'
TO_NUMBER = 'This is your number. Make sure you are adding +91 in beginning'
""" MAILGUN CONFIGURATION """
MAILGUN_API_KEY = "You can find in your Mailgun dashboard"
SANDBOX_URL = "You can find in your Mailgun dashboard"
SENDER_MAIL = "Mail address of Mailgun. You can find in your dashboard"
RECIPIENT_MAIL = "Write Your mail"
""" TELEGRAM CONFIGURATION """
bolt_api_key = "XXXX" # This is your Bolt Cloud API key
device_id = "XXXX" # This is the device ID and will be similar to BOLTXXXX
# where XXXX is some numbers
telegram_chat_id = "@XXXX" # This is the channel ID of the created Telegram channel.
# Paste after @ symbol.
telegram_bot_id = "botXXXX" # This is the bot ID of the created Telegram Bot.
# Paste after bot text.
""" BOLT IOT CONFIGURATION """
API_KEY = "This is your Bolt Cloud account API key"
DEVICE_ID = "This is the ID of your Bolt device"
FRAME_SIZE = 10
MUL_FACTOR = 6
Note: You have to replace all the above value with your credentials. You can find the first four values in Twilio dashboard and the last two in Bolt Cloud dashboard. You can change the FRAME_SIZE and MUL_FACTOR as per your convenience.
3. Algorithm of code:
step-1: Fetch the latest sensor value from the Bolt device.
step-2: Store the sensor value in a list, that will be used for computing z-score.
step-3: Compute the z-score and upper and lower threshold bounds for normal and anomalous readings.
step-4: Check if the sensor reading is within the range for normal readings.
step-5:If it is not in range, send the SMS.
step-6: Wait for 5 seconds.
step-7: Repeat from step 1.
4. Create another folder named as anomaly.py
by using the code
sudo nano anomaly.py
5. In this folder add the combined code for SMS, Email, Telegram alert.
Complete Code
import json,time,math,statistics,conf,requests
from boltiot import Bolt,Sms,Email
def send_telegram_message(message):
url = "https://api.telegram.org/" + conf.telegram_bot_id + "/sendMessage"
data = { "chat_id": conf.telegram_chat_id,
"text": message
}
try:
response = requests.request(
"GET",
url,
params=data
)
print("This is the Telegram response")
print(response.text)
telegram_data = json.loads(response.text)
return telegram_data["ok"]
except Exception as e:
print("An error occurred in sending the alert message via Telegram")
print(e)
return False
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=0
Zn = factor*math.sqrt(history_data[frame_size-1])+Zn
Low_bound = history_data[frame_size-1]-Zn
High_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_MAIL,conf.RECIPIENT_MAIL)
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_value= int(data['value'])
sensor_valuec = sensor_value/10.24
print ("The current sensor value is : "+str(sensor_valuec))
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] :
buzz=mybolt.digitalWrite('1',"HIGH")
print(buzz)
print("Anomaly of the temperature occured because of increase in temperature sending an alert messages")
""" SMS """
print ("The temperature level increased suddenly. Sending an SMS")
response = sms.send_sms("Someone has opened the fridge door.The temperature has raised to:"+str(sensor_valuec)+"degree celcius")
print("This is the response ",response)
""" TELEGRAM """
message = "Alert! Someone has opened the fridge door. The current temperature is " + str(sensor_valuec)
telegram_status = send_telegram_message(message)
print("This is the Telegram status:", telegram_status)
""" MAIL """
print("Making request to Mailgun to send an email")
response = mailer.send_email("Alert","Someone has opened the fridge door.The Current temperature sensor value is " +str(sensor_valuec))
response_text = json.loads(response.text)
print("Response received from Mailgun is:"+str(response_text['message']))
print(message.sid)
elif sensor_value < bound[1]:
buzz=mybolt.digitalWrite('1',"HIGH")
print(buzz)
print("Anomaly of the temperature occured because of increase in temperature sending an alert messages")
""" SMS """
print ("The temperature level decreased suddenly. Sending an SMS")
response = sms.send_sms("The temperature has decreased to : "+str(sensor_valuec)+"degree celcius")
print("This is the response ",response)
""" TELEGRAM """
message = "Alert! Sensor value has decreased The current value is " + str(sensor_valuec)
telegram_status = send_telegram_message(message)
print("This is the Telegram status:", telegram_status)
""" MAIL """
print("Making request to Mailgun to send an email")
response = mailer.send_email("Alert","The Current temperature sensor value is " +str(sensor_valuec))
response_text = json.loads(response.text)
print("Response received from Mailgun is:"+str(response_text['message']))
history_data.append(sensor_value);
except Exception as e:
print ("Error",e)
time.sleep(5)
Screen Shot of typed code for the convenience and reference.
Anomaly Detection-
Z score analysis
Output Message-
1. Email Alert (via Mailgun)
2. Message Alert (via Telegram)
3. SMS Alert (via Twilio)
- In case of any query visit https://forum.boltiot.com/
- For access to the BoltIoT training visit https://shop.boltiot.com/
Comments