Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Prajwal Gupta C R
Published © GPL3+

Network Strength Indicator

IoT device that indicates current internet strength and alerts the user in case of sudden increase or decrease in internet speed.

IntermediateFull instructions provided5 hours283
Network Strength Indicator

Things used in this project

Hardware components

Bolt WiFi Module
Bolt IoT Bolt WiFi Module
×1
LED (generic)
LED (generic)
×2
Buzzer
Buzzer
×1
Male/Female Jumper Wires
Male/Female Jumper Wires
×2

Software apps and online services

Bolt Cloud
Bolt IoT Bolt Cloud
Bolt IoT Bolt Python Library
Telegram
The telegram mobile app is used to send alerts to the users.

Story

Read more

Code

config.py

Python
Configuration file
bolt_api_key = "XXXX"         # Bolt Cloud API Key
device_id = "BOLTXXXX"        # Device ID of the Bolt Module                                            
telegram_chat_id = "@XXXX"    # Telegram channel ID. Paste after @                                 
telegram_bot_id = "botXXXX"   # Telegram bot ID.
FRAME_SIZE = 5                # Frame Size for Z score analysis
MUL_FACTOR = 15               # Multiplication Factor for Z score analysis

main.py

Python
Main file
import math
import statistics
import speedtest  # To find the internet speed
import requests
import json
import time
from boltiot import Bolt  # To control the bolt module
import config   # importing configuration file

mybolt = Bolt(config.bolt_api_key, config.device_id)


def find_speed():
    """Returns the download and upload speed in Mbps"""
    try:
        st = speedtest.Speedtest()
        down = st.download()/1e6
        up = st.upload()/1e6
    except:
        print("Please check your internet connection")
        return 0, 0
    return down, up


def send_telegram_message(message):
    """Sends message via Telegram
       Returns true if message was successfully delivered"""
    url = "https://api.telegram.org/" + config.telegram_bot_id + "/sendMessage"
    data = {
        "chat_id": config.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


def write_pin_value(pin, val):
    """Writes analog output to the given pin
       Returns True if the value was successfully written"""
    try:
        response = mybolt.analogWrite(pin, val)
        data = json.loads(response)
        if data["success"] != 1:
            print("Request not successfull")
            print("This is the response->", data)
            time.sleep(15)
    except Exception as e:
        print("Something went wrong when writing pin value")
        print(e)
        time.sleep(15)
        return False
    return True


def translate(value, left_min=0, left_max=150, right_min=0, right_max=255):
    """Converts the value of internet signal into appropriate
       voltage/analog output for bolt WiFi module"""
    if value > 150:
        return 255
    left_span = left_max - left_min
    right_span = right_max - right_min
    scale = right_span/left_span
    value_scaled = (value - left_min)*scale+right_min
    return int(value_scaled)


def compute_bounds(history_data, frame_size, factor):
    """Used to compute bounds for Z-score analysis
       Returns the upper and lower bounds"""
    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]


# Make sure that all pins are in OFF state
write_pin_value('0', 0)
write_pin_value('1', 0)
write_pin_value('2', 0)
write_pin_value('3', 0)
write_pin_value('4', 0)

pin1 = '1'  # First LED pin (Download speed)
pin2 = '3'  # Second LED pin (Upload speed)
pin3 = '0'  # Buzzer pin
download_history = []
upload_history = []
while True:
    # Obtain the download and upload speed
    download, upload = find_speed()

    # Switching OFF the buzzer in case it was ON
    write_pin_value(pin3, 0)

    if write_pin_value(pin1, translate(download)):
        print("Download Speed is:", download, "Mbps")
        bound = compute_bounds(download_history, config.FRAME_SIZE, config.MUL_FACTOR)
        if not bound:
            req_data_count = config.FRAME_SIZE - len(download_history)
            print("Not enough data to compute Z-score. Need ",
                  req_data_count, " more data points")
        else:
            if download > bound[0]:
                message = "Enjoy the moment.Your download speed is a blazing " \
                          + str(download) + " Mbps"
                send_telegram_message(message)
                write_pin_value(pin3, 255)
                time.sleep(5)
            elif download < bound[1]:
                message = "Check your net connection.Your download speed is " \
                          + str(download) + " Mbps"
                send_telegram_message(message)
                write_pin_value(pin3, 200)
                time.sleep(5)
        download_history.append(download)

    if write_pin_value(pin2, translate(upload)):
        print("Upload Speed is:", upload, "Mbps")
        bound = compute_bounds(upload_history, config.FRAME_SIZE, config.MUL_FACTOR)
        if not bound:
            req_data_count = config.FRAME_SIZE - len(upload_history)
            print("Not enough data to compute Z-score. Need ", req_data_count,
                  " more data points")
        else:
            if upload > bound[0]:
                message = "Enjoy the moment.Your upload speed is a blazing " \
                          + str(upload) + " Mbps"
                send_telegram_message(message)
                write_pin_value(pin3, 100)
                time.sleep(5)
            elif upload < bound[1]:
                message = "Check your internet connection.Your upload speed is "\
                          + str(upload) + " Mbps"
                send_telegram_message(message)
                write_pin_value(pin3, 50)
                time.sleep(5)
        upload_history.append(upload)

Credits

Prajwal Gupta C R
1 project • 0 followers
Contact

Comments

Please log in or sign up to comment.