0% found this document useful (0 votes)
195 views

IOT Proj - Report 1

This document presents a project report on an IoT-based smart energy meter reading and billing system using Raspberry Pi. The system was developed by 5 students under the guidance of Dr. S. Jeeva. The system aims to intelligently control electrical appliances like bulbs based on environmental conditions like humidity and light intensity to conserve energy. It also computes power consumption throughout the day and generates bills which can be paid online. This prototype could achieve energy conservation at households. The report includes sections on objectives, block diagram, project outcomes, requirements, project code, findings, conclusion and future enhancements.

Uploaded by

Diksha Nasa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
195 views

IOT Proj - Report 1

This document presents a project report on an IoT-based smart energy meter reading and billing system using Raspberry Pi. The system was developed by 5 students under the guidance of Dr. S. Jeeva. The system aims to intelligently control electrical appliances like bulbs based on environmental conditions like humidity and light intensity to conserve energy. It also computes power consumption throughout the day and generates bills which can be paid online. This prototype could achieve energy conservation at households. The report includes sections on objectives, block diagram, project outcomes, requirements, project code, findings, conclusion and future enhancements.

Uploaded by

Diksha Nasa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

IOT BASED SMART ENERGY METER READING AND

BILLING SYSTEM USING RASPBERRY PI AND POWER


MANAGEMENT USING AI

A PROJECT REPORT

Submitted by

Diksha Nasa [Reg No: RA1911042010003]


Abhishek Arora [Reg No: RA1911042010015]
Parnika Sharma [Reg No: RA1911042010028]
Nirnay Mahapatra [Reg No: RA1911042010039]
Avi Singh [Reg No: RA1911042010042]

Under the Guidance of

Dr. S. Jeeva
(Assistant Professor, Department of Data Science and Business Systems)

In partial fulfilment of the Requirements for the Degree of

BACHELOR OF TECHNOLOGY

DEPARTMENT OF DATA SCIENCE AND BUSINESS SYSTEMS


FACULTY OF ENGINEERING AND TECHNOLOGY
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
KATTANKULATHUR – 60320

1
ABSTRACT
Energy is a very important aspect for any household, industries, agriculture and so. Managing the energy
efficiently and conserving it intelligently for appliances is very much important.

Towards this, there has been lot of research work carried out in developing some smart lighting system
pertaining to room for conserving the energy. In one another research, researchers have developed IOT based
Smart home system for monitoring the usage of power to avoid any kind of anomaly.

In none of the research, researchers have worked towards automating the appliance control towards
conserving the energy. Most of them concentrate on controlling the appliances using android devices.

So, with the upcoming of machine-to-machine communication where devices can be connected wirelessly
leading to IOT, we here have developed an IOT based Smart Energy Meter system where appliances like Bulb
to start with are controlled wirelessly based on humidity and light intensity information. These inputs are used
towards controlling the appliances intelligently rather than just switching on or off for the line 2. In addition,
the system also keeps computing throughput the day power consumption of the appliances which gives the
user knowledge on power being consumed over a period of time. And bill will be generated and bill payment
window will be open for the payment. These details are updated in Cloud server. This prototype system
developed can achieve energy conservation at every household.

2
ACKNOWLEDGEMENT
First and foremost, we would like to express our gratitude to our Mentor, Dr. S. Jeeva
, who was a continual source of inspiration. He pushed us to think imaginatively and urged us to do
this homework without hesitation. His vast knowledge, extensive experience, and professional
competence in IoT enabled us to successfully accomplish this project. This endeavor would not have
been possible without his help and supervision. We could not have asked for a finer mentor in our
studies. This initiative would not have been a success without the contributions of each and every
individual. We were always there to cheer each other on, and that is what kept us together until the
end.
We would like to thank SRM Institute of Science and Technology for providing us with the
opportunity to work on the project “IOT BASED SMART ENERGY METER READING AND
BILLING SYSTEM USING RASPBERRY PI AND POWER MANAGEMENT USING AI”. Last
but not least, we would like to express our gratitude to our family, siblings, and friends for their
invaluable assistance, and we are deeply grateful to everyone who has contributed to the successful
completion of this project.

3
INDEX

S. No. Title Page No.

1 Abstract 2

2 Acknowledgement 3

3 Introduction 5

4 Literature Survey 6

5 Objectives 7

6 Block Diagram 8

7 Project Outcome 9

8 Requirements 10

9 Project Code 11

10 Project Findings 27

11 Conclusion 30

12 Future Enhancements 31

13 References 32

4
CHAPTER 1

INTRODUCTION

Increasing economic growth and consumption patterns are leading to ever growing demand for
energy. Since most of the energy supply is from fossil fuels, the resource is depleting thus increasing
cost of energy. Burning fossil fuels has also increased concentration of carbon-di-oxide in the
environment leading to extreme weather patterns. Hence it is imperative that Industries and
commercial enterprises take steps to reduce energy wastage, become energy efficient and reduce
costs.

Industry in India consumes 45% of the 900 billion Units of power produced. 35% of electric power
produced is lost, and the losses are due to Transmission & Distribution (16%), theft (10%),
Inefficiencies among users (10%). The 10% inefficiencies are largely among the industrial and
commercial users who have high KVA HT connections. Inefficiency can also arise due to harmonic
problems, faulty wiring, feedback from sub systems, and neighboring electrical systems. This leads
to a drop in power factor and higher utilization of energy leading to higher rate slabs and penalties.
Some organizations like Data centers measure Power Usage effectiveness where units consumed per
annum is much higher than that required to power their total equipment. All these are applicable to
industries like SMEs, cement, steel, auto, heat treatment/cooling, food processing, chemicals,
plastics, textiles, commercial spaces using HVAC equipment, hospitals, hotels etc.

Research has been carried out employing Raspberry Pi3 for monitoring the Temperature and
humidity data and controlling the same resulting in an Automated temperature and humidity control
using IOT Research also been carried out in developing smart home monitor and control system.

In addition to the above, research carried out employing IOT Technology for automatic lighting and
control in room using raspberry pi.

In none of the research, system been developed towards controlling the electrical appliance usage
based on environmental condition which could ultimately reduce the energy consumption of home.

5
CHAPTER 2

LITERATURE STUDY

[1] IOT Based Smart Energy Meter for Efficient Energy Utilization in Smart
Grid (2018).
Efficient energy utilization plays a very vital role for the development of smart grid in power system. So,
proper monitoring and controlling of energy consumption is a chief priority of the smart grid. The
existing energy meter system has many problems associated to it and one of the key problem is there is
no full duplex communication. To solve this problem, a smart energy meter is proposed based on Internet
of Things (IOT). The proposed smart energy meter controls and calculates the energy consumption using
ESP 8266 12E, a Wi-Fi module and uploads it to the cloud from where the consumer or producer can
view the reading. Therefore, energy analyzation by the consumer becomes much easier and controllable.
This system also helps in detecting power theft. Thus, this smart meter helps in home automation using
IoT and enabling wireless communication which is a great step towards Digital India.

[2] Smart energy is metering and power theft control using Arduino & GSM
(2017)
Energy theft is a very common problem in countries like India where consumers of energy are increasing
consistently as the population increases. Utilities in electricity system are destroying the amounts of
revenue each year due to energy theft. The newly designed AMR used for energy measurements reveal
the concept and working of new automated power metering system but this increased the Electricity theft
forms administrative losses because of not regular interval checkout at the consumer's residence. It is
quite impossible to check and solve out theft by going every customer's door to door. In this paper, a new
procedure is followed based on MICROCONTROLLER Atmega328P to detect and control the energy
meter from power theft and solve it by remotely disconnect and reconnecting the service (line) of a
particular consumer. An SMS will be sent automatically to the utility central server through GSM module
whenever unauthorized activities detected and a separate message will send back to the microcontroller in
order to disconnect the unauthorized supply. A unique method is implemented by interspersed the GSM
feature into smart meters with Solid state relay to deal with the non-technical losses, billing difficulties,
and voltage fluctuation complication.

[3] A Novel IOT based Smart Energy Meter for Residential Energy Management
in Smart Grid Infrastructure (2021)
The increased energy consumption followed by development in renewable energy generation have
resulted in tremendous challenge to energy industry. Pursuing the requirement of increased energy
efficiency have resulted in the research and development of intelligent energy networks as the future
energy network. Smart Electricity Energy Meters can be considered as the basic fundamental component
of the future intelligent network or smart grid, measuring the energy flow and exchanging information on
energy consumption between utilities and consumers and also monitoring and controlling home
appliances and devices with consumer information. In this paper, the authors propose an IOT based
Smart Energy Meter with Arduino and ESP8266 Wi-Fi unit which can provide information of electricity
bill by SMS or E-mail and can also provide energy monitoring usage anytime and anywhere in the world.

6
CHAPTER 3

OBJECTIVES

Smart energy metering technique was implemented to make the measurement of electricity consumption
simple and to specify the amount of energy consumed by the consumer in a day-to-day basis whenever
the threshold value is crossed.

• Measurement of energy units.


• Measurement of other important electric components.
• Tariff distribution.
• Indications of increase humidity to prevent water damage to product.
• Use ML model to predict power consumption based on data collected by the sensor

7
CHAPTER 4

BLOCK DIAGRAM

POWER IOT
SUPPLY

DHT11 BILLING &


PAYMENT
SENSOR

LIGHT
INTENSITY HOME LIGHT
RASPBERRY PI LINE
SENSOR
CONTROLLER -1

INA219
SENSOR SWITCH

BUZZER
RELAY
WITH
LIGHT

LCD HUMIDITY
DISPLAY LINE - 2

8
CHAPTER 5

PROJECT OUTCOME

The existing Smart Home and Energy Management system have looked more into controlling the
appliances and also managing the hazards for electrical faults. In none of the research, system has been
developed towards energy conservation by monitoring the environmental conditions and accordingly
controlling the appliance usage accordingly.

So, with the upcoming of Machine-to-Machine communication called IOT, we here have developed an
IOT Based Energy Management System where environmental sensors like Temperature and light
intensity sensor employed and reading sensed are sent to Raspberry pi Microcontroller. Based on sensed
reading, the Raspberry pi microcontroller is programmed to control the appliance usage accordingly. The
graphical information on power consumption versus time for all appliances with varying environmental
conditions is uploaded. Then this uploaded data when used with the ML model, can predict the power
consumption.

➢ Room temperature checking by temperature sensor.

➢ Light Intensity checking by LDR sensor.

➢ Voltage, Current measuring by INA219 sensor, based on voltage and current calculating Power,
Energy and rupees. Now we will check the bill is more than 50 rupees then we will send the
message to person “PAY YOUR BILL”.

➢ Line 1 - in this line we are using light, while light intensity will be darkness then we will turn on
the light and energy counting will start, otherwise light will be off.

➢ Line 2 – This line for rain/water detection, here high humidity will detect using switch and light,
while switch will on then light will on in line 2. means someone humidity is high, so we will
notify to person by message “IS IT RAINING? SAVE DEVICE FROM WATER” and alarm will
turn ON.

➢ In IOT we will upload temperature, light intensity, Energy and Rupees. All things will Display on
LCD.

➢ In software Energy Bill pdf will be generate if Bill cost >=0. And payment window will open for
the payment.

9
CHAPTER 6

REQUIREMENTS

6.1 Hardware requirements

1. Raspberry Pi
2. DHT11 sensor
3. LDR sensor
4. INA219 sensor
5. GREEN LED(line 1)
6. RED LED(line 2)
7. RELAY
8. BUZZER
9. LCD DISPLAY

6.2 Software Requirements

1. RASPBIAN OS
2. Python

10
CHAPTER 7

PROJECT CODE

7.1 Smart Energy meter and Power Management


"""
sudo apt-get install build-essential python-dev
git clone git://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
sudo python setup.py install
sudo python3 setup.py install

sudo pip install twilio


sudo pip3 install twilio

pip3 install pillow


sudo apt-get install python-pil.imagetk
pip install reportlab
pip3 install reportlab
"""
import os
import sys
import time
import serial
import random
import http.client # for python3
import urllib
import RPi.GPIO as GPIO
import Adafruit_DHT
from twilio.rest import Client
import report
from signal import signal, SIGTERM, SIGHUP, pause
from rpi_lcd import LCD
from time import sleep
from ina219 import INA219
import os
from twilio.rest import Client

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

from tkinter import *


import tkinter.messagebox
from PIL import Image,ImageTk

import tkinter as tk

import time
11
import tkinter.ttk as ttk
import tkinter.font as font

pay = 0

#********************************************************************

account_sid ="ACb400d76879ae85a94573f2e0a297ffb6" # Put your Twilio


account SID here
auth_token ="a3ac12aafa68011636b6aa541d04d4f6"
client = Client(account_sid, auth_token)

def safe_exit(signum, frame):


exit(1)

lcd = LCD()

TH_pin = 13
TH_name = Adafruit_DHT.DHT11
ldr_pin = 21
led_pin = 16
SWITCH_pin = 12
RELAY_PIN = 25
buzzer_pin = 20

ina = INA219(shunt_ohms=0.1,
max_expected_amps = 0.6,
address=0x40)

ina.configure(voltage_range=ina.RANGE_16V,
gain=ina.GAIN_AUTO,
bus_adc=ina.ADC_128SAMP,
shunt_adc=ina.ADC_128SAMP)

inavoltage = 0
inacurrent = 0
inapower= 0
v=0
i=0
p=0
newenergy = 0
billamount = 0
oldbill = 0
newbillamount = 0
gHUMI=0
gTEMP=0
gLDR =0
gPOWER = 0
gENERGY = 0
gBILL = 0
paid = 0

GPIO.setup(SWITCH_pin ,GPIO.IN)
12
GPIO.setup(led_pin,GPIO.OUT)
GPIO.setup(RELAY_PIN,GPIO.OUT)
GPIO.setup(buzzer_pin,GPIO.OUT)

GPIO.output(led_pin, GPIO.LOW)
GPIO.output(RELAY_PIN, GPIO.LOW)
GPIO.output(buzzer_pin, GPIO.LOW)
#********************************************************************

#LDR sensor===============================================

def rc_time (ldr_pin):

count = 0
GPIO.setup(ldr_pin, GPIO.OUT)
GPIO.output(ldr_pin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(ldr_pin, GPIO.IN)

while (GPIO.input(ldr_pin) == GPIO.LOW):


count += 1

return count

#===============================================
def stopwatch(seconds):
start = time.time()
#time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
#print "loop cycle time: %f, seconds count: %02d" %
(time.clock() , elapsed)
time.sleep(1)

#===============================================

def gui():
def result(Id):

R4=tkinter.Toplevel()
R4.geometry('400x200')
R4.title('Result')
image=Image.open('result.jpg')
image=image.resize((400,200))
photo_image=ImageTk.PhotoImage(image)
label1=tkinter.Label(R4,image=photo_image)
label1.place(x=0,y=0)

result=Label(R4,text="Payment Sucessfully
Done",fg="green",font=('algerian',15,'bold'))
result.place(x=10,y=50)
pay = 1
13
R4.mainloop()
def pay_mode1():
def create_payement1():
Id=ID.get()
Units1=Units.get()
price1=price.get()
result(Id)

R2=tkinter.Toplevel()
R2.geometry('400x400')
R2.title('Payment Page')
image=Image.open('pay2.jpg')
image=image.resize((400,400))
photo_image=ImageTk.PhotoImage(image)
label1=tkinter.Label(R2,image=photo_image)
label1.place(x=0,y=0)

la=Label(R2,text="Enter Details",font=('algerian',15,'bold'))
la.place(x=100,y=50)

lblInfo1=Label(R2,text="card num",fg="black",font=("bold",13))
lblInfo1.place(x=50,y=140)

lblInfo=Label(R2,text="Exp Date",fg="black",font=("bold",13))
lblInfo.place(x=50,y=180)

lblInfo=Label(R2,text="cvc",fg="black",font=("bold",13))
lblInfo.place(x=50,y=220)

ID=Entry(R2,width=20,font=("bold",13),highlightthickness=2)
ID.place(x=180,y= 140 )

Units=Entry(R2,width=20,font=("bold",13),highlightthickness=2)
Units.place(x=180,y=180 )

price=Entry(R2,width=20,font=("bold",13),highlightthickness=2)
price.place(x=180,y=220 )

signUpbt = Button(R2,text =
"Pay",width=12,height=2,fg="black",font=('algerian',10,'bold'),justify='center',bg="light
green",command=create_payement1)
signUpbt.place(x =120,y=300)

R2.mainloop()

def paymode(Id):

R2=tkinter.Toplevel()
R2.geometry('400x400')
R2.title('Payment Page')
14
image=Image.open('pay.jpg')
image=image.resize((400,400))
photo_image=ImageTk.PhotoImage(image)
label1=tkinter.Label(R2,image=photo_image)
label1.place(x=0,y=0)

la=Label(R2,text="Select Payment Mode",font=('algerian',15,'bold'))


la.place(x=100,y=50)
crdbutton = Button(R2,text =
"",width=2,height=2,fg="black",font=('algerian',10,'bold'),justify='center',bg="light
blue",command=pay_mode1)
crdbutton.place(x =50,y=140)

DebitButton = Button(R2,text =
"",width=2,height=2,fg="black",font=('algerian',10,'bold'),justify='center',bg="light
blue",command=pay_mode1)
DebitButton.place(x =50,y=210)

lblInfo1=Label(R2,text="credit
card",fg="black",font=("bold",13),width=15,height=2)
lblInfo1.place(x=130,y=140)

lblInfo=Label(R2,text="Debit
card",fg="black",font=("bold",13),width=15,height=2)
lblInfo.place(x=130,y=210)
R2.mainloop()
def second_page():
def create_payement():
Id=ID.get()
Units1=Units.get()
price1=price.get()
paymode(Id)
R2=tkinter.Toplevel()
R2.geometry('400x400')
R2.title('Payment Page')
image=Image.open('result.jpg')
image=image.resize((400,400))
photo_image=ImageTk.PhotoImage(image)
label1=tkinter.Label(R2,image=photo_image)
label1.place(x=0,y=0)

la=Label(R2,text="Enter Details",font=('algerian',15,'bold'))
la.place(x=100,y=50)

lblInfo1=Label(R2,text="ID",fg="black",font=("bold",13))
lblInfo1.place(x=50,y=140)

lblInfo=Label(R2,text="Units",fg="black",font=("bold",13))
lblInfo.place(x=50,y=180)
lblInfo=Label(R2,text="price",fg="black",font=("bold",13))
lblInfo.place(x=50,y=220)
ID=Entry(R2,width=20,font=("bold",13),highlightthickness=2)
ID.place(x=180,y= 140 )
15
Units=Entry(R2,width=20,font=("bold",13),highlightthickness=2)
Units.place(x=180,y=180 )

price=Entry(R2,width=20,font=("bold",13),highlightthickness=2)
price.place(x=180,y=220 )

signUpbt = Button(R2,text =
"Pay",width=12,height=2,fg="black",font=('algerian',10,'bold'),justify='center',bg="light
blue",command=create_payement)
signUpbt.place(x =120,y=300)

R2.mainloop()

R1=Tk()
R1.geometry('600x500')
R1.title('Home Page')
image=Image.open('Homepage.jpg')
image=image.resize((600,500))
photo_image=ImageTk.PhotoImage(image)
label1=tkinter.Label(R1,image=photo_image)
label1.place(x=0,y=0)

la=Label(R1,text="SMART ELECRICITY ",font=('algerian',15,'bold'))


la.place(x=200,y=100)

Registerbt = Button(R1,text = "PAY


HERE",width=15,height=2,font=('algerian',15,'bold'),justify='center',bg="light
blue",relief=SUNKEN,command=second_page)
Registerbt.place(x =200 ,y=245)

R1.mainloop()

#===============================================
print (' ')
print ('ENERGY METER SYSTEM')
lcd.clear()
lcd.text("ENERGY METER",1)
lcd.text(" SYSTEM",2)
time.sleep(1)

while(1):
energy1 = 0
energy2 = 0

print ("**************************************")
print ("")

#******DHT11*****************************************************************
***

16
humidity , temperature = Adafruit_DHT.read_retry(TH_name,TH_pin)
gTEMP = temperature
gHUMI = humidity
print ('TEMP : ', temperature)
print ('HUM : ', humidity)
print ("")
lcd.clear()
lcd.text("Temp = {0} C".format(temperature),1)
lcd.text("HUMI = {0} %".format(humidity),2)
time.sleep(2)

#******LDR*******************************************************************
*
gLDR = rc_time(ldr_pin)
print ('Intensity = ',gLDR)
lcd.clear()
lcd.text("Intensity: {0}".format(gLDR),1)
lcd.text("",2)
time.sleep(1)

if( gLDR <= 40000):

GPIO.output(led_pin,GPIO.HIGH)
print('NIGHT TIME')
print ("")
lcd.clear()
lcd.text("NIGHT TIME",2)
time.sleep(1)

print ('CALCULATING ENERGY....')


lcd.text("CALCULATING",1)
lcd.text("ENERGY.......",2)
stopwatch(1)

v = ina.voltage()
i = ina.current()
p = ina.power()
lcd.clear()
lcd.text('{0:0.1f}V {1:0.1f}mA'.format(v, i),1)
lcd.text('{0:0.1f} Watts'.format(p/1000),2)
gPOWER = p
print ('voltage=', v,"V")
print ('current=', i,"mA")
print ('power=', p,"W")
print ("")
time.sleep(2)

energy1 = p/100
#energy2 = energy1/5
newenergy = newenergy + energy1
gENERGY = newenergy

print ("Total Energy= {0:0.1f} U".format(newenergy))


17
lcd.clear()
lcd.text("Total Energy= {0:0.1f} U".format(newenergy),1)
lcd.text(" ",2)
time.sleep(2)

billamount = newenergy*10
gBILL = billamount
print ('BILL AMOUNT = {0:0.1f} Rs'.format(billamount))
print ("")
lcd.clear()
lcd.text("BILL AMOUNT= {0:0.1f} Rs".format(billamount),1)
lcd.text(" ",2)
time.sleep(2)
else:
GPIO.output(led_pin,GPIO.LOW)
print('DAY TIME')
print("")
lcd.clear()
lcd.text("DAY TIME",2)
time.sleep(2)

if( billamount >0):

print('PAY YOUR ENERGY BILL')


lcd.clear()
lcd.text("PAY YOUR ENERGY",1)
lcd.text(" BILL",2)
time.sleep(1)

message = client.messages.create (
from_ = '+15735704289',
body = 'METER ID : 55145, PAY YOUR ENERGY BILL',
to = '+919810310982')
print(message.sid)

# bill pdf generating


report.rpt(gENERGY,billamount)
print("Bill Generated")
time.sleep(1)

# bill payment generating


gui()
time.sleep(1)

newenergy = 0
billamount = 0

#*** LINE 2 ******************************************************

if (humidity > 80):

18
print ('IS IT RAINING ? SAVE DEVICE FROM WATER')
print ("")
GPIO.output(RELAY_PIN, GPIO.HIGH) # relay on

GPIO.output(buzzer_pin,GPIO.HIGH)
time.sleep(0.1)
GPIO.output(buzzer_pin,GPIO.LOW)
time.sleep(0.1)
GPIO.output(buzzer_pin,GPIO.HIGH)
time.sleep(0.1)
GPIO.output(buzzer_pin,GPIO.LOW)
time.sleep(0.1)
GPIO.output(buzzer_pin,GPIO.HIGH)
time.sleep(0.1)
GPIO.output(buzzer_pin,GPIO.LOW)
time.sleep(3)

GPIO.output(RELAY_PIN, GPIO.LOW) # relay off


time.sleep(1)

else:
GPIO.output(RELAY_PIN, GPIO.LOW) # relay off
GPIO.output(buzzer_pin,GPIO.LOW)
print ('SAFE...SAFE...SAFE...')
print ("")
time.sleep(1)

#**** IOT (THINGSPEAK) *****************************************

parameter=urllib.parse.urlencode({'field1':gTEMP,'field2':gHUMI,'field3':gLDR,'field4':gPOWE
R,'field5':gENERGY,'key':'KYY050UMUNQMG4F6'})
headers={"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
conn=http.client.HTTPConnection("api.thingspeak.com:80")
conn.request("POST","/update",parameter,headers)
response=conn.getresponse()
print (response.status,response.reason)
data=response.read()
time.sleep(2)
conn.close()

print("DATA UPLOADED TO IOT")


lcd.clear()
lcd.text("DATA UPLOADED",1)
lcd.text(" TO IOT",2)
time.sleep(2)

#*********************************************

19
7.2 ML Algorithms

7.2.1 LSTM
import pandas as pd
df = pd.read_csv('/content/feed (1).csv')
df.head()
df.isnull().sum()
df.drop(['created_at', 'entry_id'], axis=1, inplace=True)
df.dtypes
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt # plotting
import numpy as np # linear algebra
import os # accessing directory structure
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
df.head()
df['Temperature'] = pd.to_numeric(df['Temperature'], errors='coerce')
df['Humidity'] = pd.to_numeric(df['Humidity'], errors='coerce')
df['LDR'] = pd.to_numeric(df['LDR'], downcast='float')
values = df.values
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
scaled = scaler.fit_transform(values)
from math import sqrt
from sklearn.model_selection import train_test_split
from numpy import concatenate
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from pandas import to_datetime
from pandas import to_numeric
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from matplotlib import pyplot
import tensorflow as tf
from keras.layers import LSTM, GRU, Bidirectional, Dropout, Concatenate, CuDNNLSTM,
CuDNNGRU, SimpleRNN, Conv1D,GlobalMaxPooling1D,TimeDistributed, MaxPooling1D,
Flatten
# convert series to supervised learning
def series_to_supevised(dataset, n_in=1, n_out=1, dropnan=True):

20
num_vars = 1 if type(dataset) is list else dataset.shape[1]
df = DataFrame(dataset)
cols, names = list(), list()
# input sequence (t-n, ....t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j+1, i)) for j in range(num_vars)]
# forecast sequence (t, t+1 .... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j+1)) for j in range(num_vars)]
else:
names += [('var%d(t+%d)' % (j+1, i)) for j in range(num_vars)]
# put it all together
agg = concat(cols, axis=1)
agg.columns = names
# drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
return agg
# frame as supervised learning
reframed = series_to_supevised(scaled, 1, 1)
# drop columns we don't want to predict
print("reframed: ", reframed.shape, "reframed head: ", reframed.head())
# split into train and test sets
values = reframed.values
X = values[:,:29]
Y = values[:,3]
#Y2 = dataset[:,16]
# Split Data to Train and Test
X_Train, X_Test, Y_Train, Y_Test = train_test_split(X, Y, test_size=0.8)
# reshape input to be 3D [samples, timesteps, features]
X_Train = X_Train.reshape((X_Train.shape[0], 1, X_Train.shape[1]))
X_Test = X_Test.reshape((X_Test.shape[0], 1, X_Test.shape[1]))
print(X_Train.shape[1])
print(X_Train.shape[2])
model = Sequential()
model.add((LSTM(40,return_sequences=True, input_shape=(X_Train.shape[1],
X_Train.shape[2]))))
model.add(Dropout(0.2))
model.add((LSTM(20,return_sequences=True)))
model.add(Dropout(0.3))

21
model.add((LSTM(20,return_sequences=False)))
model.add(Dropout(0.2))
model.add(Dense(1,activation='ReLU'))
model.compile(loss='mse', optimizer='adam', metrics=['accuracy', 'mse','mae','mape','msle'])
# fit
callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=5)
history = model.fit(X_Train, Y_Train, epochs=70, batch_size=128,callbacks=[callback],
validation_data=(X_Test, Y_Test), verbose=2, shuffle=True)
model.save('history.h5')
y_test_dummies = pd.get_dummies(Y_Test).values
print('Shape of Label tensor: ', y_test_dummies.shape)
from keras.models import load_model
model = load_model('history.h5')
scores = model.evaluate(X_Test, y_test_dummies)
LSTM_accuracy = scores[1]*100
print('Test accuracy: ', scores[1]*100, '%')
print(model.metrics_names)
model.evaluate(X_Test,Y_Test)

7.2.2 XGBOOST
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.pipeline import Pipeline
import pandas as pd
from xgboost import XGBRegressor
df= pd.read_csv('feed.csv')
df=df.drop('created_at',axis=1)
df.head()
df= df.drop('entry_id',axis=1)
df.head()
df['Temperature'] = pd.to_numeric(df['Temperature'], errors='coerce')
df['Humidity'] = pd.to_numeric(df['Humidity'], errors='coerce')
df['LDR'] = pd.to_numeric(df['LDR'], downcast='float')
X=df[['Temperature','Humidity','LDR']]
y=df['Power']
X_train, X_test, y_train, y_test = train_test_split(X, y)
pipeline = Pipeline([('scaler', MinMaxScaler()), ('regressor', XGBRegressor())])
pipeline.fit(X_train, y_train)
r2 = pipeline.score(X_test, y_test)
print(f"XGBoost regressor r2: {r2}")

22
7.2.3 Linear Regression
import pandas as pd
df = pd.read_csv("feed.csv")
df.head()
df=df.drop('created_at',axis=1)
df.head()
df= df.drop('entry_id',axis=1)
df.head()
df['Temperature'] = pd.to_numeric(df['Temperature'], errors='coerce')
df['Humidity'] = pd.to_numeric(df['Humidity'], errors='coerce')
df['LDR'] = pd.to_numeric(df['LDR'], downcast='float')
from sklearn import linear_model
import numpy as np
np.isnan(df)
np.where(np.isnan(df))
np.nan_to_num(df)
df_new = df[np.isfinite(df).all(1)]
print(df_new)
X = df_new[['Temperature', 'Humidity','LDR']]
y = df_new['Power']
regr = linear_model.LinearRegression()
regr.fit(X, y)
df.dtype
predictedPow = regr.predict([[28.0, 76.0,14616.0]])
print(predictedPow)
y=df_new.Power
x=df_new.drop('Power',axis=1)
x.head()
y.head()
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
print("shape of original dataset :", df_new.shape)
print("shape of input - training set", x_train.shape)
print("shape of output - training set", y_train.shape)
print("shape of input - testing set", x_test.shape)
print("shape of output - testing set", y_test.shape)

from sklearn.linear_model import LinearRegression


# creating an object of LinearRegression class
LR = LinearRegression()
# fitting the training data
LR.fit(x_train,y_train)
# Score
score_lr = LR.score(x_test, y_test)
score_lr
df.dtypes
# Predictions
preds = LR.predict(x_test)

7.2.4 KNN
# Performance
pd.DataFrame({ 'True Value': np.exp(y_test),
23
'Prediction': np.exp(preds)}).head(5)
from sklearn.neighbors import KNeighborsRegressor
# Instance and fit
knn_model = KNeighborsRegressor(n_neighbors=5).fit(x_train, y_train)
# Score
score_knn = knn_model.score(x_test, y_test)
score_knn
# Predictions
preds = knn_model.predict(x_test)
# Performance
performance = pd.DataFrame({ 'True Value': y_test,
'Prediction': preds,
'Error': y_test - preds})
# View
performance
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(15,7))
# Errors
ax_x= performance['True Value']
ax_y= performance['Prediction']
yerr= performance['Error']
plt.scatter(range(len(yerr)), yerr, alpha=.5)
plt.title('Homogeneous Errors - KNN', size=15);
plt.hlines(y=0, xmin=0, xmax=11000, linestyle='--', color='white', alpha=.5);
#plt.ylim(-.3, .3);
from scipy.stats import probplot
#QQ Plot
probplot(yerr, dist='norm', plot=plt);
lrLog_model = LinearRegression().fit(x_test, y_test)
# Predictions
preds = lrLog_model.predict(x_test)
# Performance
LR_log_performance = pd.DataFrame({ 'True Value': np.exp(y_test),
'Prediction': np.exp(preds),
'Error': np.exp(y_test) - np.exp(preds)})
plt.figure(figsize=(15,7))
# Errors
ax_x= LR_log_performance['True Value']
ax_y= LR_log_performance['Prediction']
yerr= LR_log_performance['Error']
plt.scatter(range(len(yerr)), yerr, alpha=.5)
plt.title('Homogeneous Errors - Log LR', size=15);
plt.hlines(y=0, xmin=0, xmax=11000, linestyle='--', color='white', alpha=.5);
#plt.ylim(-.3, .3);
probplot(yerr, dist='norm', plot=plt);
pd.DataFrame({'Linear Regression':[score_lr],

'KNN Regression': [score_knn]})

y_prediction = LR.predict(x_test)
y_prediction
# importing r2_score module
24
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
# predicting the accuracy score
score=r2_score(y_test,y_prediction)
print('r2 score is ',score)
print('mean_sqrd_error is==',mean_squared_error(y_test,y_prediction))
print('root_mean_squared error of is==',np.sqrt(mean_squared_error(y_test,y_prediction)))

25
CHAPTER 8

PROJECT FINDINGS

8.1 Visualizations

26
8.2 ML model comparisons

8.2.1 LSTM

Long Short-Term Memory Network is an advanced RNN, a sequential network, that allows information
to persist. It is capable of handling the vanishing gradient problem faced by RNN. A recurrent neural
network is also known as RNN is used for persistent memory. For our project this model portrayed the
highest accuracy.
Accuracy: 89.9 %

8.2.2 Linear Regression

Linear Regression is a machine learning algorithm based on supervised learning. It performs


a regression task. Regression models a target prediction value based on independent variables. It is
mostly used for finding out the relationship between variables and forecasting. Different regression
models differ based on – the kind of relationship between dependent and independent variables they are
considering, and the number of independent variables getting used. The negative score indicates that the
relationship between variables in our project is not linear and this model is a bad fit.
Accuracy Score: -0.5356934518440728

27
8.2.3 KNN

KNN regression is a non-parametric method that, in an intuitive manner, approximates the association
between independent variables and the continuous outcome by averaging the observations in the same
neighborhood. The accuracy is low for this model for out project.
Accuracy Score: 0.31585921481266

8.2.4 XGBoost

XgBoost stands for Extreme Gradient Boosting, which was proposed by the researchers at the University
of Washington. It is a library written in C++ which optimizes the training for Gradient Boosting. This
model is also not the correct fit for our product.
Accuracy Score: -0.24610841922238058

28
CHAPTER 9

CONCLUSION

In the era of technology advancement, monitoring and controlling of energy consumption is very important.
The proposed smart energy meter system for home management makes use of a raspberry pi processor. In
this project, an energy consumption monitoring and controlling smart energy meter is proposed which
would increase awareness of energy consumption amongst devices and users. Energy awareness at the
domestic level enables the user to control the power state of the devices as per their needs which
minimizes the energy use.

Thus, using such smart energy meters in home management system is very important. This project achieves
the objectives of
• Improving awareness of energy consumption at domestic level.
• Monitoring and controlling energy consumption at home through IoT.
• Water damage detection.

Future enhancement of the smart energy system is likely an important aspect. It is possible to connect all the
energy consuming appliances at home to IoT and smart meter to monitor and control individual electronic
devices automatically without any human interference.

29
CHAPTER 10

FUTURE ENHANCEMENTS

The project captures sensor data and supplies power to the LED as well as uploads the data to “ThinkSpeak”
cloud. To further enhance this project, API can be used to dynamically import data collected by ThinkSpeak
to the ML model in order to get real-time predictions.
As well as payment gateway APIs maybe utilized in order to complete the payment process in the project
GUI itself. A switch maybe attached to raspberry pi, which when switched on can detect theft of electricity.
The current model can only handle voltage up to 5V but the standard voltage of household is 220V
therefore, this project can further be enhanced to work with voltage higher than currently acceptable.

30
CHAPTER 11

REFERENCES

[1] M. Lavanya , P. Muthukannan, Y.S.S. Bhargav, V. Suresh, “IoT Based Automated


Temperature and Humidity Monitoring and Control”, Journal of Chemical and
Pharmaceutical Sciences ISSN: 0974- 2115.

[2] Abhijeet Rajurkar, Onkar Shinde, Vinayak Shinde, Bhushan Waghmode,”Smart Home
Control and Monitor System Using Power of IoT’s”, International Journal of Advanced
Research in Computer and Communication Engineering Vol. 5, Issue 5, May 2016.

[3] Suresh Sankaranarayanana , Au Thien Wanb , Aida Harayani Pusac ,” Smart Home
Monitoring using Android and Wireless Sensors”, I.J. Engineering and Manufacturing, 2014,
2, 12-30.

[4] Suresh,S, Anusha, H.N.S, Rajath,T, Soundarya, P and Prathyusha, V (2016), "Automatic
Lighting and Control System for Classroom", Proceedings of 2016 IEEE International
conference on ICT in Business, Industry and Government, Indore, Madhyapradesh, pp.1-6

[5] Shamika Kshirsagar, Mr.D.E. Upasani, “Energy Management System for Smart Home”,
International Research Journal of Engineering and Technology (IRJET) Volume: 03 Issue: 06
| June-2016.

[6] Vinay sagar K ,Kusuma S, ” Home Automation Using Internet of Things”, International
Research Journal of Engineering and Technology (IRJET) Volume: 02 Issue: 03 | June-2015.

[7] Ms. Hlaing Thida Oo Dr. Khin Than Mya Ms. Nyain Nyain Lwin,” IoT based Home Energy
Management system for Rural Area in Myanmar”, ICT Virtual Organization of ASEAN
Institutes and NICT ASEAN IVO Forum 2016

31

You might also like