Basavesh MP
Published © GPL3+

Anomaly Detection - A Capstone Project

Detecting the sudden rise or fall of temperature using a simple machine learning algorithm.

IntermediateFull instructions provided2 hours713
Anomaly Detection - A Capstone Project

Things used in this project

Hardware components

Bolt WiFi Module
Bolt IoT Bolt WiFi Module
×1
Temperature Sensor
Temperature Sensor
×1
USB-A to Micro-USB Cable
USB-A to Micro-USB Cable
×1
Jumper wires (generic)
Jumper wires (generic)
×3
Breadboard (generic)
Breadboard (generic)
×1

Software apps and online services

Snappy Ubuntu Core
Snappy Ubuntu Core
Bolt Cloud
Bolt IoT Bolt Cloud

Story

Read more

Schematics

Circuit Fig

Connections

Sensor

Sensor connection.

Code

capstone.py

Python
Main program
import requests, json, time, math, statistics
import cap_conf

from boltiot import Bolt

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]

def send_telegram_message(message):
    """Sends message via Telegram"""
    url = "https://api.telegram.org/" + cap_conf.telegram_bot_id + "/sendMessage"
    data = {
        "chat_id": cap_conf.telegram_chat_id,
        "text": message
    }
    try:
        response = requests.request(
            "POST",
            url,
            params=data
        )
        print("This is the Telegram URL")
        print (url)
        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

mybolt = Bolt(cap_conf.bolt_api_key, cap_conf.device_id)
history_data = []

while True:
    print ("Reading sensor value")
    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 ("Sensor value is: "+ str(data['value']))
    sensor_value=0
    try:
        sensor_value = int(data['value'])
        temperature = (100 * sensor_value)/1024

    except e:
        print("There was an error while parsing the response: ",e)
        continue

    bound = compute_bounds(history_data,cap_conf.FRAME_SIZE,cap_conf.MUL_FACTOR)
    if not bound:
        required_data_count = cap_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(2)
        continue

    try:
        if sensor_value > bound[0] :
            print ("Temperature increased suddenly. Sending msg. ")
            message = "Aleart! Someone OPENED your fridge.\n\nThe current temperature inside your fridge is " + str(round(temperature, 1)) + " degree celsius."
            telegram_status = send_telegram_message(message)
            print ("This is the Telegram status:", telegram_status)

        elif sensor_value < bound[1]:
            print ("Temperature decreased suddenly. Sending msg.")
            message = "Alert! Someone CLOSED your fridge. The current temperature inside your fridge is " + str(round(temperature, 1)) + " degree celsius."
            telegram_status = send_telegram_message(message)
            print ("This is the Telegram status:", telegram_status)

        history_data.append(sensor_value);

    except Exception as e:
        print ("Error",e)
    time.sleep(2)

cap_conf.py

Python
Configuration file for the main program.
"""Configurations for capstone.py"""


bolt_api_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

device_id = "BOLTxxxxxxx"

telegram_chat_id = "@tempalert4lm35"

telegram_bot_id = "botxxxxxxxxxxx:AAGNXeoGgsYNtXCUdN82rMlzuJ1-xxxxxxx"

FRAME_SIZE = 15

MUL_FACTOR = 10

Credits

Basavesh MP
2 projects • 3 followers

Comments