import config, json, time,requests, math, statistics
from boltiot import Bolt, Sms, Email
mybolt= Bolt(config.API_KEY,config.DEVICE_ID)
sms=Sms(config.SID, config.AUTH_TOKEN, config.TO_NUMBER, config.FROM_NUMBER)
history_data=[]
mailer=Email(config.MAILGUN_API_KEY, config.SANDBOX_URL, config.SENDER_EMAIL, config.RECIPIENT_EMAIL)
min=0
max=5
def send_telegram_message(message1):
url = "https://api.telegram.org/" +config.telegram_bot_id+"/sendMessage"
data ={"chat_id": config.telegram_chat_id, "text": message1}
try:
tresponse = requests.request("POST", url, params=data)
print("This is the telegram URL")
print(url)
print("This is the telegram response")
print(tresponse.text)
telegram_data = json.loads(tresponse.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=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]
while True:
print("Reading sensor value")
rresponse = mybolt.analogRead('A0')
data = json.loads(rresponse)
x=int(data['value'])
temperature= (100*x)/1024
print("Sensor value is :" +str(data['value']))
print(temperature)
try:
if temperature>max or temperature<min:
print("Making request to mailgun to send an alert email")
response= mailer.send_email("Alert","the current temperature is :"+str(temperature))
response_text = json.loads(response.text)
print("Response received from mailgun is:"+str(response_text))
print("Making request to Twilio to send a SMS")
sresponse= sms.send_sms("the Current tmperature is " +str(temperature))
print("Response received from Twilio is:" +str(sresponse))
print("Status of SMS at Twilio is :" +str(sresponse.status))
message1="Alert! Sensor value is "+str(x)+"temperature is "+str(temperature)
telegram_status = send_telegram_message(message1)
print("This is the Telegram status:", telegram_status)
except Exception as e:
print ("Error occured: Below are the details")
print(e)
bound= compute_bounds(history_data, config.FRAME_SIZE, config.MUL_FACTOR)
if not bound:
required_data_count= config.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
try:
if x > bound[0]:
print("The temperature increased suddenly. Sending an SMS.")
result= sms.send_sms("Someone opened the fridge door.")
print("This is the response", result)
history_data.append(x);
except Exception as e:
print ("Error",e)
time.sleep(10)
Comments
Please log in or sign up to comment.