Final Project
Final Project
Appliances Consumption
Submitted to University of Madras in partial fulfilment of the requirement for the award of
the degree of
BATCH (2021-2024)
BY
GUIDE SIGNATURE
I feel that I have come to the finest part of this project at this juncture it is worth mentioning
about the people, who with their constant inspiration guidance and blessing made all this
happen.
I take this opportunity to express my sincere gratitude to the principal In-Charge Rev. Fr. Dr.
ARULMANI JOSEPH M.S.W., NET of Christ College, Kilachery for permitted to carry
out this research work.
I take this opportunity to express my sincere gratitude to the Dean Science Rev.Fr. V.
PRADEEP CHRISTOPHER M.SC., MPhil, B. Ed., of Christ College, Kilachery for
having permitted to carry out this research work.
I take this opportunity to express my sincere gratitude to the Head of the Department of the
Computer Science Dr. K. DEEPA SUNDARI MCA., M.Phil., of Christ College, Kilachery
for providing opportunity to carry out this research work.
I am duty bound to express my sincere thanks to the beloved Asst. Professor B. PADMINI
M.Sc., B.Ed., M.Phil., Department of Computer Application, for being my guide and
proving valuable suggestions for my research work.
I submit my heartful thanks to my parents who supported me financially & morally and to all
my relatives who have always been a source of inspiration to me.
ii
DECLARATION
By
HERMAN BRITTO A
(Reg. No 222108663)
iii
TABLE OF CONTENTS
CHAPTER TITLE PAGE NO
LIST OF FIGURES vi
ABSTRACT viii
1. INTRODUCTION 1
1.1 OVERVIEW 1
2. SYSTEM ANALYSYIS 13
4. SYSTEM DESIGN 26
4.4 ER DIAGRAM 31
iv
5. SYSTEM ARCHITECTURE 32
6. SYSTEM IMPLEMENTATION 43
7. SYSTEM TESTING 58
8. CONCLUSION 63
8.1 CONCLUSION 63
APPENDIX 65
SAMPLE SCREENS 82
REFERENCE 91
v
LIST OF FIGURES
vi
LIST OF ABBREVIATIONS
SVM Support Vector Machine
vii
Abstract
Smart cities can enhance our daily lives by providing comprehensive smart services such as
smart transportation and energy. Electricity is one of the most popular forms of energy.
Currently, the electricity distribution companies are responsible for taking readings to
determine the energy consumption of the final consumer; this activity is performed by field
personnel contractors, which is exposed to risks to their physical integrity, either by climate
or social situation. When the owners of a residential building receive their monthly electric
energy bill, the information does not discriminate the consumption behaviour of household
appliances and loads. If consumers were able to identify those devices which have a higher
consumption based on historical consumption data or baseline consumption, they could take
actions that effectively impact its electrical energy consumption. The electricity information
of each equipment can help to manage electrical system supply and demand in view of
electricity supplier and user. The aim of this project is to develop a Web App for smart
energy meter reading and appliance usage monitor and control system. Its architecture is built
on a centralized principle; interaction with users is carried out through a web interface.
Custom-tailored data visualization dashboard, which is usually created inside the user
interface offered by a Cloud platform. This project is proposed to automate the collection of
electricity consumption data and do an analysis with the ability to visualize and detail certain
indicators for minimizing the costs of electricity consumption. It provides authorization for
connected smart meters, collection and storage of their data, device management, software
management, alerts, and other functions. Analytics module that allows monitoring of trends,
creation of rule-based alerts, generation of comparative reports, etc.
viii
CHAPTER 1
INTRODUCTION
1.1. Overview
Electricity is a very important commodity needed for human life. It is used in houses for
heating, cooking, ironing and other important aspects of living. Industries use it for powering
plants and production. Offices also use it for their daily operation like powering the
computers, use of air condition and so on. It is generated from many sources which include,
the thermal, coal, nuclear and hydro. The existence of sufficient supply of electricity helps to
propel economic growth and stability of a country. This in turn gives rise to a lot of economic
activities and increase in Gross Domestic Product. In recent years, energy consumption has
become one of the major problems because of its impact on the economic, financial spheres.
In Saudi Arabia, there are many factors that cause increasing energy consumption in non-
residential buildings. In the CoC, there are many problems that cause increased consumption.
Extreme weather is one of the main problems, causing summer temperature increases to
increase energy consumption through repeated use of air conditioning. In winter, the heat
causes increased energy consumption through repeated use of the heater, depending on the
type, size, operation time and wattage consumed per hour. The number of devices has a large
load on energy in general; the increase in the number will inevitably increase the
consumption of energy. In the CoC, there are many devices and servers. The growing number
means increasing energy consumption. If we consider the workday, there are many lectures
which mean there is excessive consumption of energy compared to the weekend. In addition
to the practical examinations period, there are many uses of the devices. The presence of
many cafeterias in the college is an additional reason for the increase in consumption because
of the presence of a number of devices such as refrigerators, coffee makers and microwaves
in each cafeteria. The presence of multiple devices around us is important and their quality is
furthermore important to perform the best performance, but the low quality will not perform
properly. The quality of devices in the field of electric power is very important because of the
lack of quality whether it is old-fashioned or being affected by weather affects their
consumption. The quality of the devices affects the consumption of energy where the lower
quality the greater consumption.
2
The term “smart meter” initially referred to the functionality of measuring the electricity used
and/or generated and the ability to remotely control the supply and cut off when necessary. It
was called AMR that used one-way communication and capable of automated monthly reads,
one way outage (or last gasp) and tamper detection, and simple load profiling. Over time the
AMR capability was extended into short term interval (hourly or less) data capture, on-
demand reads and linking into and reading other commodities. A major upgrade of
functionality occurred after integration of the meters with two-way communication
technology which has been called advanced metering integrated (AMI). The upgrade
included the incorporation of service switching, time - based rates, remote programming,
power quality measure, and a dashboard-type user interface for real - time usage monitoring
into the AMR. Although the term smart meter started to be used only after the SG initiatives,
it can be seen that the features and functionality of the meters evolved from the manually read
meters of the past to the AMI meters with dashboard interfaces and two-way communication
capability.
The smart meter is the measurement and information capture device and, in many instances,
connected to the communication device called smart meter gateway to establish a secure
energy-information network. The gateway could receive and communicate real-time
information from supplier, be a point of control for appliances, start and stop energy supply,
etc. It could also have a user interface called the “in-home-display” (IHD), which displays
energy consumption, cost, tariffs with real-time updates, etc. The smart meter can be
connected to the smart meter gateway which in turn communicates with different appliances
(washing machine, refrigerator, etc), local generation as well as heating, ventilation, and air
conditioning (HVAC). The measurements and information captured by the smart meter are
displayed via the IHD. The smart meter could directly communicate the consumption
3
information with the utility, but the gateway communicates with the next-level gateway in the
SG infrastructure to pass information for aggregation, demand–response activities, as well as
to utilities.
1.1.2. Stakeholders
The stakeholder involvement and benefits are summarized in Table I under each main
stakeholder group. For operations and markets, the information acquired from smart meters
will be vital for planning operations, responding to market demands, and anticipating changes
and disruptions to reduce risks to secure energy supply.
Although there are smart meters of varying technology and design, there is a common overall
process for data collection, communication, and analysis leading to decision support. The
smart metering process in fact could be thought of as part of the activation and functioning of
the SG. The smart meter gathers data locally and transfers via a local area network (LAN) to
a data collection point. There are two key categories of data collected as mentioned earlier.
Usage or consumption data refers to the actual electricity usage measured in kilowatt hours
(kWh), and this is read and transmitted in regular intervals. Depending on the particular
4
deployment and region, the frequency of data collection can vary from 1 h to every 15 min.
The issues faced with data collection and the implications and techniques for making use of
this data are further discussed in detail in the following sections. In terms of the processing of
data, some data processing could be carried out at the local collection points, but in most
cases, the data are transferred to the utilities’ central collection center via a wide area network
(WAN). The data collected at the utility are used for a number of business purposes such as
billing, network and service monitoring, profiling, prediction and planning.
Load forecasting is the predicting of electrical power required to meet the short term, medium
term or long-term demand. The forecasting helps the utility companies in their operation and
management of the supply to their customers.
Electrical load forecasting is an important process that can increase the efficiency and
revenues for the electrical generating and distribution companies. It helps them to plan on
their capacity and operations in order to reliably supply all consumers with the required
energy.
1. Enables the utility company to plan well since they have an understanding of the future
consumption or load demand.
2. Minimize the risks for the utility company. Understanding the future long-term load helps
the company to plan and make economically viable decisions in regard to future
generation and transmission investments.
5
3. Helps to determine the required resources such as fuels required to operate the generating
plants as well as other resources that are needed to ensure uninterrupted and yet
economical generation and distribution of the power to the consumers. This is important
for short-, medium-, and long-term planning.
4. The load forecasting helps in planning the future in terms of the size, location and type of
the future generating plant. By determining areas or regions with high or growing
demand, the utilities will most likely generate the power near the load. This minimizes the
transmission and distribution infrastructures as well as the associated losses.
5. Helps in deciding and planning for maintenance of the power systems. By understanding
the demand, the utility can know when to carry out the maintenance and ensure that it has
the minimum impact on the consumers. For example, they may decide to do maintenance
on residential areas during the day when most people are at work and demand is very low.
6. Maximum utilization of power generating plants. The forecasting avoids under generation
or over generation.
6
getting accurate data on consumption behaviour due to changes in factors such as pricing and
the corresponding demand based on such a price change. Load forecasting task is difficult
due to the complex nature of loads which may vary depending on the seasons and the total
consumption for two similar seasons may vary. It is sometimes difficult to accurately fit the
numerous complex factors that affect demand for electricity into the forecasting models. In
addition, it may not be easy to obtain an accurate demand forecast based on parameters such
as change in temperature, humidity, and other factors that influence consumption. The utility
may suffer losses if they do not understand and decide on an acceptable margin of error in
short term load forecasting.
Load forecasting is mainly done for three-time horizon based on the time of the requirement
by the utility company. Long-Term Load Forecasting (LTLF): It is mainly for system
planning, typically covers a period of 10 to 20 years. Medium-Term Load Forecasting
(MTLF): It is mainly for the scheduling of fuel supplies and maintenance usually covers a
few weeks. Short-Term Load Forecasting (STLF): It is done for the day-to-day operation and
scheduling of the power system. This is usually from an hour to a day. Methods of Load
Forecasting: In modern era many computer tools are available for load forecasting. Starting
with the use of conventional methods in computer there are many soft techniques for load
forecasting. Long Term Load Forecasting Techniques and Medium-Term Load Forecasting:
Approach and methods for both the LTLF and MTLF are nearly same since the load variation
in both periods can be approximated to each other. Some of the important methods are Trend
7
Analysis, End Use Analysis, Econometrics, Neural Network, and Multiple Linear Regression.
Short Term Load Forecasting: Soft techniques have taken over the conventional methods due
to their advantages in the use and the results. The soft techniques used for load forecasting
are: Similar Day Lookup Approach: This method is somehow similar to the conventional
method. It is based on searching historical data for any day with the same characteristics,
such as weather, humidity, day of the week, dates (if holiday or any special day) as that of the
present considered day. The historical data can be used in linear combination or regression to
make a trend analysis.
Smart meters will enable to set up dynamic tariff structures to improve efficiency in
electricity markets by better representing the costs of producing and delivering electricity at
different times. Consumers could benefit from these if they choose more flexible tariff
arrangements that better represent their electricity cost. To determine the price of electricity
as well as the tariffs, retailers consider payments to distributors for services, wholesale
electricity cost, retail services cost, as well as costs of any regulatory requirements. Smart
meter data enable deeper analysis for understanding the dynamics of supply and demand
resulting in better forecasting the needs, enabling pricing intelligence. Smart meter data can
be used to analyze and plan different rate structures, without discriminating by demographics
of low income, etc.
Deep learning is a subset of AI and machine learning that uses multi-layered artificial neural
networks to deliver state-of-the-art accuracy in tasks such as object detection, speech
recognition, language translation, and others.
8
Deep learning differs from traditional machine learning techniques in that they can
automatically learn representations from data such as images, video or text, without
introducing hand-coded rules or human domain knowledge. Their highly flexible
architectures can learn directly from raw data and can increase their predictive accuracy when
provided with more data.
Deep learning isn't a single approach but rather a class of algorithms and topologies that you
can apply to a broad spectrum of problems.
Deep learning architectures into supervised and unsupervised learning and introduces several
popular deep learning architectures: convolutional neural networks, recurrent neural networks
(RNNs), long short-term memory/gated recurrent unit (GRU), self-organizing map (SOM),
autoencoders (AE) and restricted Boltzman machine (RBM). It also gives an overview of
deep belief networks (DBN) and deep stacking networks (DSNs).
Supervised learning refers to the problem space wherein the target to be predicted is clearly
labelled within the data that is used for training.
9
Convolutional neural networks
A CNN is a multilayer neural network that was biologically inspired by the animal visual
cortex. The architecture is particularly useful in image-processing applications.
GRU networks
In 2014, a simplification of the LSTM was introduced called the gated recurrent unit. This
model has two gates, getting rid of the output gate present in the LSTM model. These gates
are an update gate and a reset gate. The update gate indicates how much of the previous cell
contents to maintain. The reset gate defines how to incorporate the new input with the
previous cell contents.
Sentiment Analysis
Sentiment analysis is the process of understanding/ analysing customer sentiments through
natural language processing, text analysis, and statistics. A company tries to understand the
customers' sentiments based on what people say and how they are stating it to understand
what the customers feel about that company. They can also classify the statements as
positive, negative, or neutral impressions. Specifically, companies can find customers'
sentiments in the form of tweets, comments, reviews, etc.
10
huge volumes of data, data tagging, semantic indexing, quick data retrieval, and streamlining
discriminative tasks. Sophisticated algorithms based on Deep Learning methods are key to
accuracy and efficiency during real-time data processing.
Examples of Deep Learning in big data: Automated extraction of complex data, learning from
huge amounts of unsupervised data, simulations, social media, classification, prediction, etc.
Aim: The aim of the project "smart meter firmware using LSTM for forecasting and
monitoring and controlling household electrical appliances consumption and take online
reading" is to develop a system that can track and manage household electrical appliance
energy consumption, forecast energy usage, and take online readings. The system will use
LSTM (Long Short-Term Memory) algorithms to analyze the historical data and forecast the
future energy usage of households.
Objectives:
Develop a web application to provide a user interface for consumers to view their
electrical appliance energy consumption data, set usage limits, view generated bills, and
make online payments.
Develop a web admin portal to manage the smart meter data, train the LSTM model, and
monitor household energy usage.
11
Develop an LSTM algorithm to analyze historical energy consumption data and forecast
future energy usage.
Integrate the LSTM algorithm with the web application to enable consumers to view their
forecasted energy usage.
Test the system and ensure that it meets the specified requirements and objectives.
The scope of the project "smart meter firmware using LSTM for forecasting and monitoring
and controlling household electrical appliances consumption and take online reading"
includes the development of a web-based smart meter firmware system that allows the web
admin to train smart meter data, the consumer to view the energy consumption of electrical
appliances individually, set usage limits, view generated bills, and pay them online. It also
includes the capability of Reading Personnel to log in and generate readings. The project
aims to provide an efficient and effective way of forecasting and monitoring household
electrical appliances' energy consumption and to help consumers manage their energy
consumption better, ultimately reducing energy bills and promoting energy efficiency. The
project is expected to be developed using Python Flask and MySQL.
The project "smart meter firmware using LSTM for forecasting and monitoring and
controlling household electrical appliances consumption and take online reading" is
important for several reasons:
Energy conservation: The project can help households monitor their energy consumption
and adjust their usage accordingly to conserve energy, thus contributing to environmental
sustainability.
Cost savings: With the ability to monitor their energy consumption, households can
identify areas where they can reduce their energy usage, resulting in cost savings on their
energy bills.
12
Convenience: The project allows households to monitor their energy consumption
remotely, which is more convenient than traditional methods of meter reading.
Accurate forecasting: By using LSTM for forecasting, the project can provide accurate
predictions of energy usage, which can help households, plan their energy usage more
effectively.
13
CHAPTER 2
SYSTEM ANALYSIS
Eight traditional machine learning methods are used to build household appliance energy
consumption prediction models: support vector machine (SVM), k nearest neighbour (KNN),
random forest (RF), and extreme random forest (ERF), Support Vector Regression (SVR),
Artificial Neural Network (ANN), Autoregressive Integrated Moving Average (AIMA),
Multiple Linear Regression (MLR).
SVM is a kind of generalized linear classifier for binary classification of data according to
supervised learning.
KNN can be used for regression by obtaining the nearest neighbours of a sample and
assigning the average of the properties of these neighbours to the sample to obtain the
properties of the sample. Another improved method is to give different weights to the
influence of neighbours of different distances on the sample, such as the weight is inversely
proportional to the distance.
The ERF algorithm is very similar to the RF algorithm. It is composed of many decision
trees, introduces more randomization than random forests, and can solve the variance
problem more efficiently. Its computational complexity is also slightly reduced.
14
SVR is a modified version of the SVM devised by Müller et al. to address the time series
forecasting problem. It has gained increasing attention over the past decades, especially in
electricity demand forecasting. The main objective of SVR is to find a hyperplane function
that can recognize patterns in the given time series data. One advantage of this model is that
the upper boundary of the generalized error, rather than the learning error, is minimized. SVR
was selected as a benchmark model because previous studies have proven that an SVR-based
model can yield satisfactory performance across various electricity demand forecasting. In
this study, the hyper parameters of SVR, penalty factor and gamma, were experimentally
determined as 100 and 0.001, respectively.
An ANN is a mathematical model designed to simulate the processes and functionality of the
human brain. Generally, the main objective in this context involves finding a relationship that
can automatically map output to input through the training stage, by which the network is
iteratively trained to minimize forecasting error. ANN has the advantage of being applicable
to multivariate models and capable of describing non-linear relationships among output and
input from given historical data. A back-propagation ANN, combining a back-propagation
algorithm with a feedforward multi-layer perceptron is the most widely used network
structure and was adopted in this study; the momentum and learning-rate parameters were
experimentally determined as 0.2 and 0.3, respectively.
ARIMA, the most well-known statistical method for time series analyses, can model complex
patterns and forecast in univariate time series data. The ARIMA model function has three
important factors, denoted as p, d, and q, which represent the autoregressive, integration, and
moving average factors, respectively. An expression of the ARIMA (p, d, q) model in general
is as follows:
MLR, one of the most common statistical regression models, was also employed as a
benchmark model. The MLR’s objective is to model the relationship among a dependent
variable and multiple independent variables. The relationship between the vector of
repressors and the dependent variable is assumed to be linear in MLR. The equation of linear
regression maps the forecasting model to the observations in the given time series, x and y
values, for forecasting purposes. An expression of the MLR model is as follows:
The resulting model is used for forecasting the y value with additional observations x.
Disadvantage
The additional cost to train personal, develop equipment, and implement new processes
for data storage
Managing public reaction and feedback concerning new meters
Making a long-term financial commitment to new hardware/software
Ensuring the security and privacy of metering dat
In this project, a hybrid model (HSBUFC) is developed based on the stacking of bi-
directional and uni-directional LSTMs followed by fully connected dense layers to achieve
the forecasts with high accuracy and low error percentages as compared to the mentioned
models.
The architectures of the uni-directional and bidirectional LSTMs are discussed. The forward
and backward passes in bi-directional LSTMs are utilized to recognize inherent patterns in
energy consumption data using past and future inputs.
16
A. UNI-DIRECTIONAL LSTMS (OR LSTMS)
LSTM is a type of Recurrent Neural Network that is classically built to process, analyse, and
forecast sequence data. The RNN model predicts based on the input of the current time step
and the output from the previous time step. In addition to the ability to utilize information
from the recurrent connections to the outputs of previous time steps, LSTMs also have
memory cells to accumulate steps over prediction sequences enabling them to perform better
with long-term dependency tasks such as energy forecasting. Also, the existence of gates and
more complex recurrent units in LSTMs enable them to control the information that is passed
through and overcome the problem of vanishing gradients.
B. BI-DIRECTIONAL LSTMS
17
The framework of the proposed hybrid stacked bi-directional uni-directional LSTM with
fully connected dense layers (HSBUFC) model is illustrated in Figure 5. HSBUFC model
consists of three types of layers: 1) Bidirectional LSTM layer, 2) Stacked Uni-directional
LSTM layers, and 3) Fully connected layers/dense layers. As discussed in the earlier section,
bi-directional LSTMs make use of both forward and backward dependencies. The temporal
long-term dependencies of the energy consumption values are extracted during the feature
learning process in two directions by the initial layer of bi-directional LSTM. Next, LSTM
layers, which are efficient in the forward dependencies, are employed in the top layers, which
receive the outputs from the lower layer after learning from the extracted comprehensive and
complex features.
Advantages
18
CHAPTER 3
SYSTEM REQUIREMENTS
Processors:
Intel® Core™ i5 processor 4300M at 2.60 GHz or 2.59 GHz (1 socket, 2 cores, 2
threads per core), 8 GB of DRAM
19
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python
is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain.
Python is currently the most widely used multi-purpose, high-level programming language.
Python allows programming in Object-Oriented and Procedural paradigms. Python programs
generally are smaller than other programming languages like Java. Programmers have to type
relatively less and indentation requirement of the language, makes them readable all the time.
Python language is being used by almost all tech-giant companies like – Google, Amazon,
Facebook, Instagram, Dropbox, Uber… etc. The biggest strength of Python is huge collection
of standard libraries which can be used for the following:
Machine Learning
GUI Applications (like Kivy, Tkinter, PyQt etc.)
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, Beautiful Soup, Selenium)
Test frameworks
Multimedia
Scientific computing
Text processing and many more.
3.3.1.1. Pandas
Pandas are a fast, powerful, flexible and easy to use open source data analysis and
manipulation tool, built on top of the Python programming language. pandas are a Python
package that provides fast, flexible, and expressive data structures designed to make working
with "relational" or "labeled" data both easy and intuitive. It aims to be the fundamental high-
level building block for doing practical, real world data analysis in Python.
20
Pandas are mainly used for data analysis and associated manipulation of tabular data in Data
frames. Pandas allow importing data from various file formats such as comma-separated
values, JSON, Parquet, SQL database tables or queries, and Microsoft Excel. Pandas allow
various data manipulation operations such as merging, reshaping, selecting, as well as data
cleaning, and data wrangling features. The development of pandas introduced into Python
many comparable features of working with Data frames that were established in the R
programming language. The panda’s library is built upon another library NumPy, which is
oriented to efficiently working with arrays instead of the features of working on Data frames.
3.3.1.2. NumPy
NumPy, which stands for Numerical Python, is a library consisting of multidimensional array
objects and a collection of routines for processing those arrays. Using NumPy, mathematical
and logical operations on arrays can be performed.
3.3.1.3. Matplotlib
21
Matplotlib is a plotting library for the Python programming language and its numerical
mathematics extension NumPy. It provides an object-oriented API for embedding plots into
applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.
3.3.1.4. Seaborn
scikit-learn is a Python module for machine learning built on top of SciPy and is distributed
under the 3-Clause BSD license.
Scikit-learn (formerly scikits. learn and also known as sklearn) is a free software machine
learning library for the Python programming language. It features various classification,
regression and clustering algorithms including support-vector machines, random forests,
22
gradient boosting, k-means and DBSCAN, and is designed to interoperate with the Python
numerical and scientific libraries NumPy and SciPy.
3.3.2. MySQL
MySQL tutorial provides basic and advanced concepts of MySQL. Our MySQL tutorial is
designed for beginners and professionals. MySQL is a relational database management
system based on the Structured Query Language, which is the popular language for accessing
and managing the records in the database. MySQL is open-source and free software under the
GNU license. It is supported by Oracle Company. MySQL database that provides for how to
manage database and to manipulate data with the help of various SQL queries. These queries
are: insert records, update records, delete records, select records, create tables, drop tables,
etc. There are also given MySQL interview questions to help you better understand the
MySQL database.
MySQL is currently the most popular database management system software used for
managing the relational database. It is open-source database software, which is supported by
Oracle Company. It is fast, scalable, and easy to use database management system in
comparison with Microsoft SQL Server and Oracle Database. It is commonly used in
conjunction with PHP scripts for creating powerful and dynamic server-side or web-based
enterprise applications. It is developed, marketed, and supported by MySQL AB, a Swedish
company, and written in C programming language and C++ programming language. The
official pronunciation of MySQL is not the My Sequel; it is My Ess Que Ell. However, you
can pronounce it in your way. Many small and big companies use MySQL. MySQL supports
many Operating Systems like Windows, Linux, MacOS, etc. with C, C++, and Java
languages.
3.3.3. WampServer
23
WampServer is a Windows web development environment. It allows you to create web
applications with Apache2, PHP and a MySQL database. Alongside, PhpMyAdmin allows
you to manage easily your database.
WampServer is a reliable web development software program that lets you create web apps
with MYSQL database and PHP Apache2. With an intuitive interface, the application
features numerous functionalities and makes it the preferred choice of developers from
around the world. The software is free to use and doesn’t require a payment or subscription.
3.3.5. Bootstrap 4
Bootstrap is a free and open-source tool collection for creating responsive websites and web
applications. It is the most popular HTML, CSS, and JavaScript framework for developing
responsive, mobile-first websites.
It solves many problems which we had once, one of which is the cross-browser compatibility
issue. Nowadays, the websites are perfect for all the browsers (IE, Firefox, and Chrome) and
for all sizes of screens (Desktop, Tablets, Phablets, and Phones). All thanks to Bootstrap
developers -Mark Otto and Jacob Thornton of Twitter, though it was later declared to be an
open-source project.
Easy to use: Anybody with just basic knowledge of HTML and CSS can start using
Bootstrap
24
Responsive features: Bootstrap's responsive CSS adjusts to phones, tablets, and desktops
Mobile-first approach: In Bootstrap, mobile-first styles are part of the core framework
3.3.6. Flask
Flask is a web framework. This means flask provides you with tools, libraries and
technologies that allow you to build a web application. This web application can be some
web pages, a blog, a wiki or go as big as a web-based calendar application or a commercial
website.
Flask is often referred to as a micro framework. It aims to keep the core of an application
simple yet extensible. Flask does not have built-in abstraction layer for database handling,
nor does it have formed a validation support. Instead, Flask supports the extensions to add
such functionality to the application. Although Flask is rather young compared to most
Python frameworks, it holds a great promise and has already gained popularity among Python
web developers. Let’s take a closer look into Flask, so-called “micro” framework for Python.
Flask was designed to be easy to use and extend. The idea behind Flask is to build a solid
foundation for web applications of different complexity. From then on you are free to plug in
any extensions you think you need. Also you are free to build your own modules. Flask is
great for all kinds of projects. It's especially good for prototyping.
25
WSGI-Web Server Gateway Interface (WSGI) has been adopted as a standard for Python
web application development. WSGI is a specification for a universal interface between the
web server and the web applications
Werkzeug-It is a WSGI toolkit, which implements requests, response objects, and other
utility functions. This enables building a web framework on top of it. The Flask framework
uses Werkzeug as one of its bases.
Jinja2 Jinja2 is a popular templating engine for Python. A web templating system combines
a template with a certain data source to render dynamic web pages.
26
CHAPTER 4
SYSTEM DESIGN
The input design of the "smart meter firmware" involves the following components:
1. Smart meter data: The firmware takes data from smart meters installed in households.
This data includes real-time energy consumption by each household appliance, as well as
historical energy consumption data.
2. User inputs: The firmware has user input fields that allow consumers to view their
energy consumption data, set usage limits, view bills, and pay them online. Reading
personnel also have input fields for logging in and generating readings.
3. Admin inputs: The firmware has input fields for the web admin to train the LSTM model
on the smart meter data and set parameters for monitoring and controlling household
energy consumption.
4. Data pre-processing: The smart meter data undergoes pre-processing before being used
by the LSTM model. This includes data cleaning, feature engineering, and normalization.
5. Training data: The firmware uses a portion of the smart meter data for training the
LSTM model to forecast future energy consumption. The training data is selected based
on certain criteria such as time frame, location, and appliance type.
6. LSTM model parameters: The admin sets the parameters for the LSTM model, such as
the number of hidden layers, the number of neurons in each layer, and the learning rate.
7. Usage limits: The consumer can set usage limits for their appliances to prevent excessive
energy consumption and save costs.
8. Payment information: Consumers enter their payment information into the firmware to
pay their energy bills online.
The output design of the "smart meter firmware" project includes various outputs that are
generated based on the input provided by the users. Some of the key output designs are:
27
1. Energy consumption data: The smart meter firmware collects and stores data on the
energy consumption of individual appliances in a household. The data is displayed in a
user-friendly manner so that the consumers can easily understand their energy usage
patterns.
2. Usage Limit Alerts: The system generates alerts to the consumers when their energy
usage exceeds the set usage limit. The alert is sent through email, SMS, or notification to
the mobile application, as per the consumer's preference.
3. Bill Generation: The system generates bills based on the energy consumed by the
consumer during a particular billing period. The bill includes details such as energy
consumption, billing rate, and the total amount to be paid.
4. Payment Confirmation: Once the consumer makes the payment, the system generates a
payment confirmation receipt that includes the payment amount, date, and other relevant
details.
5. Forecasting: The LSTM algorithm is used to forecast energy usage patterns based on
historical data. The system generates a forecast report that includes predicted energy
usage patterns, expected bills, and usage limit alerts for the upcoming period.
6. Reading Personnel Reports: The system generates reports on the readings taken by the
reading personnel. These reports include details such as the date and time of the reading,
energy consumption data, and any relevant remarks from the reading personnel.
Database: eb_forecasting
Field Type
username varchar(20)
password varchar(20)
28
id int(11)
username varchar(20) Foreign key
Start_date varchar(20)
End_date varchar(20)
unit double
amount double
Register_date varchar(20)
Field Type
id int(11)
device varchar(30)
29
electric_stove int(11)
Field Type
id int(11)
edevice varchar(50)
eb_usage Double
Id int(11)
name varchar(20)
mobile bigint(20)
email varchar(40)
Area varchar(40)
City varchar(40)
30
username varchar(20) Primary key
password varchar(20)
id int(11)
seconds int(11)
unit double
amount double
Store_date varchar(20)
status int(11)
month int(11)
year int(11)
31
4.4 ER Diagram
32
CHAPTER 5
SYSTEM ARCHITECTURE
33
5.2 Data Flow Diagram
5.2.1. Level – 0
34
5.2.2. Level – 1
35
5.2.3. Level – 2
36
5.3. UML Diagram
37
5.3.2. Use case
38
5.3.3. Activity Diagram
39
5.3.4. Sequence Diagram
40
5.3.5. Collaboration Diagram
41
5.3.6. Component Diagram
42
5.3.7. Deployment Diagram
43
CHAPTER 6
SYSTEM IMPLEMENTATION
Take Reading
Feature Extraction View Reading
Consumer
System
44
6.2 System Architecture
To implement a smart meter firmware that uses LSTM for energy consumption forecasting
and allows for monitoring and control of individual household appliances, you could follow
these steps:
1. Dataset Collection and Preparation: Collect and prepare a dataset of historical energy
consumption data for the household, including data on individual appliance usage.
3. LSTM Model Development: Develop an LSTM model that can forecast the household’s
energy consumption based on historical data. Train the model on the prepared dataset.
5. Database Integration: The LSTM model is integrated with the MySQL database to store
and retrieve the predicted values. The predicted values can be stored in the database and
used to analyze the energy consumption patterns of each appliance over time.
6. User Interface: A user interface is created to enable users to monitor and control the
energy consumption of individual appliances. The user interface can be a web application
that displays the predicted energy consumption for each appliance in real-time.
7. Integration of Smart Meter: Integrate the developed LSTM model with the smart meter
firmware to forecast the energy consumption.
8. Monitoring and Control: Develop a Python Flask web application that allows users to
monitor and control individual household appliances. The application should
communicate with the smart meter firmware and send commands to control the
appliances.
45
9. Deployment and Testing: Deploy the smart meter firmware and the Flask web
application on a suitable server and test the system thoroughly to ensure it works as
intended.
In summary, implementing a system for smart meter firmware using LSTM for forecasting
and monitoring and controlling household electrical appliances consumption with Python
Flask and MySQL involves several steps. Data collection, preprocessing, LSTM model
training, model deployment, database integration, user interface, and real-time control are the
key steps involved.
System Design for smart meter firmware using LSTM for forecasting and monitoring and
controlling household electrical appliances consumption and taking online readings with
Python Flask and MySQL, you could follow these steps:
1. Hardware requirements:
A Wi-Fi or Ethernet module for connecting the smart meter to the internet
2. Data collection:
The smart meter device will collect real-time data on the total power consumption of
the household and transmit it to a server.
The server will also collect data from the electrical sensors on the power consumption
of individual appliances.
3. Data pre-processing:
The collected data will be pre-processed before feeding it into the LSTM model.
46
4. LSTM forecasting model:
Train the model on historical data to forecast future power consumption patterns.
The LSTM model will generate a forecast of power consumption for the upcoming
hour or day.
Use the forecast generated by the LSTM model to monitor the power consumption of
the household in real-time.
Use Python Flask to develop a web interface for users to monitor their power
consumption and control individual appliances remotely.
6. Online readings:
Implement a feature for taking online readings from the smart meter device.
Use Python Flask to create an API endpoint that accepts requests from the smart
meter device and responds with the current power consumption readings.
Integrate the system with the smart grid to allow for bidirectional communication
between the smart meter and the power grid.
The system will be able to communicate with the power grid to optimize energy
usage and reduce costs.
Thus, this system would provide users with real-time monitoring and control over their
household energy consumption, while also allowing for the integration of renewable energy
sources and participation in demand response programs.
1. Web Admin logs in to the system and trains the LSTM model with historical data of
household electrical appliance consumption.
2. The LSTM model uses the historical data to forecast future energy consumption for each
household electrical appliance.
3. The Smart Meter reads the real-time energy consumption data of each household
electrical appliance and sends it to the server.
4. The server receives the real-time energy consumption data from the Smart Meter and uses
the LSTM model to predict the energy consumption of each appliance for the next
day/week/month.
5. The server then sends the predicted energy consumption data to the Smart Meter.
6. The Smart Meter controls the electrical appliances to ensure that the predicted energy
consumption is not exceeded.
7. Consumers can view the energy consumption of each electrical appliance individually
and set usage limits for each appliance through a web interface.
8. The server generates bills based on the actual energy consumption and sends them to the
consumer's account.
10. The Reading Personnel can log in to the system and generate readings for consumers.
This system flow allows for accurate forecasting, monitoring, and controlling of household
electrical appliance consumption, making it easier for consumers to manage their energy
usage and costs. It also provides Reading Personnel with a streamlined process for generating
readings for consumers.
48
The smart meter firmware project aims to develop a system that can help households monitor,
control and forecast their energy consumption. The system is designed to work with smart
meters installed in households, and it consists of a web application and a machine learning
algorithm. The web application will have three different interfaces - one for the web
administrator, one for the consumers, and one for the reading personnel. The web admin
panel allows the administrator to train the smart meter data and set usage limits for each
appliance. It also provides an interface for viewing generated bills and processing payments.
The machine learning algorithm used in this project is LSTM (Long Short-Term Memory)
which is a type of neural network that is good for forecasting time-series data. The LSTM
algorithm will be used to predict the household's energy consumption based on past data and
external factors like weather conditions. The consumer dashboard allows consumers to view
their electrical appliances' energy consumption individually and set usage limits for each
appliance. They can also view generated bills and process payments.
The reading personnel login enables the reading personnel to generate readings and update
the database. The forecasting and monitoring module utilizes LSTM to forecast and monitor
household electrical appliances consumption. The system will also have the ability to control
household appliances' energy consumption based on the usage limit set by the consumers.
This feature will be implemented using a microcontroller connected to the household
appliances. The system will be built using Python Flask and MySQL. The Flask framework
will be used to develop the web application, while MySQL will be used as the database to
store smart meter data and other related information.
Forecaster Web App incorporates the overall systems that measure, collect and analyse
electricity usage. FWA system extends beyond Advanced Meter Reading (AMR) Technology
by allowing two-way communications between the utility provider’s system and the meter.
This enables demand-response actions or remote service barring or disconnects.
49
2. Smart Metered Dataset Annotation
The dataset contains electrical consumption data for a single residential customer the data
were collected for a period of five months ranging from 11 January 2016 to 27 May 2016.
The study was conducted on one-hour resolution data. For all three architectures, the first
three years were used as the training data and the last year was used as testing data. For all
the architectures, the electricity consumption for the next 60 hours was predicted.
50
Register
Upload Previously
EB Admin Login Collected Data Set
Storage
To build and evaluate the proposed hybrid model, a real-world dataset of appliances energy
consumption is used Smart meter data from each home appliance.
IoT
Convert to digital
Meter Data from Home Cloud
and CSV format
Storage
3. Pre-processing
In this module, we need to replace the missing data by the Mean or Median of the entire
column. Soil Nutrients types are taken as feature Variables and the NULL values as well as
redundant values from the dataset are removed.
51
Previous Eb
Consumption Data Set Preprocessing
or Meter Data
3. K-means Clustering
The popularity of K-means clustering can be attributed to its simplicity and generally
satisfactory performance. K-means is also implemented in many software solutions, both
proprietary and open source, making it an easy choice for fast clustering. The greedy design
approach of the K-means algorithm can create suboptimum solutions by unfortunate initial
starting conditions and converge in local optima; a problem that can be alleviated by
rerunning the algorithm several times.
K-means
Preprocessed Data
Clustering
Appliances
Smart meter data can be regarded as signals; as such it could be advantageous to apply
techniques that leverage time series information like periodicity or autocorrelation. In Fast
Fourier transform (FFT), a frequency domain analysis technique for signals, is applied, but
several other techniques exist for analysing time series.
52
FFT Feature
Clustered Data
Extraction
Time
series
5. LSTM Classification
HSBUFC model consists of three types of layers: 1) Bidirectional LSTM layer, 2) Stacked
Uni-directional LSTM layers, and 3) Fully connected layers/dense layers. As discussed in the
earlier section, bi-directional LSTMs make use of both forward and backward dependencies.
The temporal long-term dependencies of the energy consumption values are extracted during
the feature learning process in two directions by the initial layer of bi-directional LSTM.
Next, LSTM layers, which are efficient in the forward dependencies, are employed in the top
layers, which receive the outputs from the lower layer after learning from the extracted
comprehensive and complex features.
Forecasting Pricing
6. Prediction
In this module, the Euclidean distance or Euclidean metric is the "ordinary" distance between
two points that one would measure with a ruler, and is given by the Pythagorean formula. By
using this formula as distance, Euclidean space (or even any inner product space) becomes a
metric space. The associated norm is called the Euclidean norm. Older literature refers to the
metric as Pythagorean metric.
53
The Euclidean distance between points p and q is the length of the line segment connecting
them: p.q In Cartesian coordinates, if p = (p , p ,..., p ) and q = (q , q ,..., q ) are two points in
Euclidean n space, then the distance from p to q, or from q to p is given by the following
heterogenous value difference metric.
Load
Dynamic
Forecasting
Pricing
7. Performance Analysis
In this module, the outcome is counted as true positive (TP); if the same outcome is
incorrectly classified as negative, it is counted as a false negative (FN). If the valid diagnosis
is CHD absent and it is correctly classified as negative, the outcome is counted as true
negative (TN); if the same outcome is incorrectly classified as positive, it is counted as a false
positive (FP).
𝑇𝑃+𝑇𝑁
𝑇𝑃+𝑇𝑁+𝐹𝑃+𝐹𝑁
TP
𝑇𝑃+FN
54
TN
𝑇N+FP
Euclidean
Trained Data File
Prediction
Result
Test Data visualization
Result Analysis
55
5. Billing Management: This module enables the web admin to manage the billing process
for each user. The admin can generate bills based on the energy consumption data and
view the billing history for each user.
6. Reporting: This module enables the web admin to generate reports on energy
consumption and usage patterns. The admin can view reports for each device or user, as
well as generate summary reports.
7. Alert Management: This module enables the web admin to set alerts for abnormal
energy consumption or usage patterns. The admin can set alert thresholds and receive
notifications when thresholds are exceeded.
8. System Configuration: This module enables the web admin to configure system settings,
such as time intervals for data collection, device communication settings, and other
system parameters.
8.2. Consumer
The consumer modules in the smart meter firmware system include:
1. Login: This module allows the consumer to log in to their account using their username
and password.
2. View Energy Consumption: This module enables consumers to view their energy
consumption on a per-appliance basis. Consumers can view the energy consumption of
each electrical appliance they have connected to the smart meter.
3. Set Usage Limit: This module enables consumers to set usage limits for their electrical
appliances. The system will generate an alert when the usage limit is reached, prompting
the consumer to turn off the appliance.
4. View Generated Bills: This module allows consumers to view their monthly energy bills
generated by the smart meter system.
5. Pay Bills: This module enables consumers to pay their monthly energy bills online
through the smart meter system.
6. Support: This module enables consumers to submit support requests to the system
administrators for any issues or queries they may have.
8.3. Reading Personnel
The Reading Personnel module of the smart meter firmware system is designed to enable
authorized personnel to log in and generate readings for households. It involves the following
functionalities:
56
1. Login: The Reading Personnel can log in to the system using their authorized login
credentials.
2. Generate Readings: The Reading Personnel can generate readings for households within
their designated area or location. The readings can be taken online using the smart meter
firmware system.
3. View Readings: The Reading Personnel can view the readings generated for a particular
household. This information can be used to detect any abnormalities in energy
consumption and take appropriate actions to address the issue.
4. Edit Readings: The Reading Personnel can edit the readings generated for a household in
case of errors or discrepancies. This feature ensures that accurate billing is done for the
households.
9. Notification
The Notification module in the smart meter firmware system is responsible for sending
notifications to different users based on various events or triggers. This module is
implemented to provide a seamless and user-friendly experience to the consumers and to
ensure that they are aware of any important updates or events related to their energy
consumption. Some of the important features of the Notification module include:
Real-time alerts: The Notification module can send real-time alerts to the consumers via
SMS or email whenever their energy consumption exceeds a certain threshold or when
they are nearing their usage limit. This feature helps consumers to manage their energy
consumption efficiently and avoid any unexpected bills.
Payment reminders: The Notification module can also send payment reminders to the
consumers when their bills are due. This feature helps to reduce the number of late
payments and ensures that consumers are up-to-date with their bills.
Service notifications: The Notification module can send service notifications to the
consumers when there is a scheduled maintenance or outage in their area. This feature
helps to improve the overall customer experience and reduce the number of complaints
related to service disruptions.
Customizable notifications: The Notification module provides consumers with the
ability to customize their notification settings based on their preferences. For example,
consumers can choose to receive alerts only via email or SMS, or they can select specific
events or triggers for which they want to receive notifications.
57
The Notification module is an important component of the smart meter firmware system, as it
helps to keep consumers informed and engaged with their energy consumption, bills, and
services.
10. Reporting
The reporting module is responsible for generating various reports based on the data collected
by the smart meter firmware system. This module provides different types of reports such as
usage reports, billing reports, and energy consumption reports. The usage report provides
information on the energy consumption of individual appliances in a household. This report
helps the consumer to identify high energy-consuming appliances and make necessary
adjustments to reduce energy consumption. The billing report provides information on the
energy consumption of a household and the corresponding bill generated for that particular
billing cycle. The report includes details on the energy tariff rates, energy consumption, and
the total bill amount. The energy consumption report provides information on the energy
consumption pattern of a household. This report helps the consumer to identify the peak
energy usage time and make necessary adjustments to reduce energy consumption during
those periods. The reporting module uses data analysis and visualization techniques to
generate these reports. The reports can be generated in various formats such as PDF, CSV, or
Excel, and can be accessed through the web portal or mobile application.
58
CHAPTER 7
SYSTEM TESTING
Software testing for the smart meter firmware project using LSTM for forecasting and
monitoring household electrical appliances consumption can be carried out using different
techniques such as functional testing, performance testing, security testing, and usability
testing.
1. Unit Testing: This testing involves testing individual units or components of the system,
such as functions and methods, to ensure that they are working as expected. We can write
test cases to test the functionalities of each module, such as web admin, consumer,
reading personnel, notification, and reporting modules.
2. Integration Testing: This testing involves testing the integration of different modules of
the system to ensure that they are working together seamlessly. We can test the
integration of the web admin, consumer, reading personnel, notification, and reporting
modules and ensure that they are functioning correctly and communicating with each
other.
3. System testing: This testing method involves testing the entire system to ensure that it
meets the requirements and specifications. System testing helps to identify and fix issues
that arise due to the interaction of different components of the system.
4. Security Testing: This testing involves testing the system's security features, such as
authentication and authorization, to ensure that they are functioning correctly and
preventing unauthorized access to the system and data. We can test the security features
of the system by attempting to access the system using different methods and ensuring
that the security measures are working as expected.
5. User Acceptance Testing: This testing involves testing the system's usability and user
interface to ensure that it is user-friendly and easy to use for the end-users. We can
conduct user acceptance testing by having a group of representative end-users test the
system and provide feedback on its usability and user interface.
60
Expected result: Web admin should be able to upload and train smart meter data
using LSTM algorithm.
Expected result: The system should accurately predict the energy consumption of
household appliances.
8. Test case: LSTM model forecasts energy consumption for the next month
Expected result: LSTM model accurately forecasts energy consumption for the next
day.
9. Test case: Reporting system generates report for energy consumption over a specific
period
Expected result: Reporting system generates accurate report for energy consumption
over the specified period.
Introduction
The purpose of this test report is to provide an overview of the testing process and the results
obtained for the Smart Meter Firmware project. The project aims to provide a system that
uses LSTM for forecasting, monitoring and controlling household electrical appliances
consumption, and taking online readings. The system consists of web admin, consumer, and
reading personnel modules.
Test Objective
The objective of testing is to ensure that the system meets the requirements and specifications
defined in the project. It includes testing the functionality, performance, reliability, and
usability of the system.
Test Scope
61
Testing of web admin module for managing smart meter data and generating bills
Testing of the system for forecasting, monitoring, and controlling household electrical
appliances consumption using LSTM
Test Environment
The testing was performed in a controlled environment using the following tools:
Test Results
The testing was carried out in three phases: unit testing, integration testing, and system
testing.
Unit Testing: Unit testing was performed on each module to ensure that individual functions
work as expected. The results of unit testing showed that all modules passed their respective
tests.
Integration Testing: Integration testing was performed to ensure that different modules
work together as expected. The results of integration testing showed that all modules were
able to integrate seamlessly.
System Testing: System testing was performed to test the system as a whole. The system
was tested for functionality, performance, reliability, and usability. The test results showed
that the system was able to meet all the requirements and specifications defined in the project.
62
Performance Testing: Performance testing was performed using JMeter to test the system's
performance under load. The test results showed that the system was able to handle the load
without any performance issues.
Usability Testing: Usability testing was performed to ensure that the system is user-friendly
and easy to use. The test results showed that the system was easy to use and navigate.
Test Conclusion
In conclusion, the testing process was successful, and the system was able to meet all the
requirements and specifications defined in the project. The system was found to be
functional, reliable, and user-friendly. The performance testing showed that the system was
able to handle the load without any issues. The project was completed successfully, and the
system is ready for deployment.
63
CHAPTER 8
8.1. Conclusion
In conclusion, the "smart meter firmware" project using LSTM for forecasting and
monitoring and controlling household electrical appliances consumption and take online
reading is an important and feasible project. It aims to provide consumers with the ability to
monitor and manage their energy usage, set usage limits, view generated bills, and make
payments online. The project's scope includes functionalities such as web administration for
training smart meter data, consumer access to individual appliance consumption, setting
usage limits, and generating bills. The LSTM algorithm is used for forecasting and
monitoring household electrical appliance consumption, and Python Flask and MySQL are
used for implementation. The project's feasibility study indicated that it is feasible, and the
implementation process is manageable. The project's importance lies in its potential to
contribute to energy conservation efforts, increase consumer awareness of energy
consumption, and reduce energy bills. The project was tested using black box and white box
testing methodologies, with a focus on unit testing. The test results showed that the project's
functionality was consistent with the project's objectives, and the output design met the
project's requirements. In conclusion, the smart meter firmware project has the potential to
contribute to energy conservation efforts, increase consumer awareness of energy
consumption, and reduce energy bills. The project's implementation and testing process
showed that the project is feasible and has the necessary functionality to meet its objectives.
The use of LSTM for forecasting energy consumption adds an additional layer of intelligence
to the system, making it more efficient and effective. Overall, the "smart meter firmware"
project has the potential to make a significant impact in the energy industry and empower
consumers to take control of their energy usage.
The possibilities for future enhancements are endless, and as technology continues to evolve,
there will be new opportunities to enhance the smart meter firmware for forecasting and
monitoring and controlling household electrical appliances consumption.
3. Integration with Virtual Assistants: The system can be enhanced by integrating with
virtual assistants like Alexa or Google Assistant. Users can control individual appliances
using voice commands, making the system more user-friendly.
5. Integration with Smart Grid: The system can be enhanced by integrating with the smart
grid. The smart grid can provide real-time energy pricing information, which can be used
to optimize energy consumption for individual appliances.
7. Integration with Smart Cities: The system can be enhanced by integrating with smart
cities. This can provide access to data on traffic, weather, and other factors that can affect
energy consumption. The LSTM model can be trained to incorporate this data and
provide more accurate energy consumption forecasts.
65
APPENDIX
if request.method=='POST':
name=request.form['name']
ebno=request.form['ebno']
address=request.form['address']
city=request.form['city']
area=request.form['area']
mobile1=request.form['mobile']
email=request.form['email']
rdate=date.today()
print(rdate)
mycursor = mydb.cursor()
maxid = mycursor.fetchone()[0]
if maxid is None:
maxid=1
uname="C"+str(maxid) #request.form['uname']
pass1="1234"#request.form['pass']
now = date.today()
rdate=now.strftime("%d-%m-%Y")
cursor = mydb.cursor()
66
sql = "INSERT INTO
eb_register(id,name,ebno,address,area,city,mobile,email,uname,pass,rdate) VALUES
(%s,%s,%s,%s, %s, %s, %s, %s, %s, %s, %s)"
val = (maxid,name,ebno,address,area,city,mobile1,email,uname,pass1,rdate)
cursor.execute(sql, val)
mydb.commit()
result="sucess"
#url="http://iotcloud.co.in/testmail/sendmail.php?email="+email+"&message="+message
#webbrowser.open_new(url)
with app.app_context():
mail.send(msg)
Add EB Staff
rdate=now.strftime("%d-%m-%Y")
cursor = mydb.cursor()
val = (maxid,name,area,city,mobile,email,uname,pass1)
cursor.execute(sql, val)
mydb.commit()
67
message="Dear "+name+", Your Staff ID: "+uname+" ,Password: "+pass1
#url="http://iotcloud.co.in/testmail/sendmail.php?email="+email+"&message="+message
#webbrowser.open_new(url)
with app.app_context():
mail.send(msg)
result="sucess"
EB Monitor
dc = mycursor.fetchone()[0]
if dc==0:
i=1
edata =mycursor.fetchall()
for ed in edata:
maxid1 = mycursor.fetchone()[0]
if maxid1 is None:
maxid1=1
ed1=ed[0]
68
sql2 = "INSERT INTO eb_monitor(id,uname,edevice,status,seconds,unit,month,year,device)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
val2 = (maxid1,uname,ed1,0,0,0,mon,yr,ed[1])
mycursor.execute(sql2, val2)
mydb.commit()
i+=1
#path = 'eb-data.csv'
fn=uname+".csv"
path='dataset/'+fn
df = pd.read_csv(path, header=0)
data=[]
for ss in df.values:
data.append(ss)
#print(data)
datah=['Fan','Tubelight','Television','Refrigerator','Washing Mchine','Microwave
Oven','Water Purifier','AC','Water Heater','Motor Pump','Air Cooler','Computer','Electric
Stove']
month = datetime.now().month
print(month)
gmon=0
amon=['January','February','March','April','May','June','July','August','September','October','N
ovember','December']
if month==12:
69
gmon=0
else:
gmon=month
nmonth=amon[gmon]
tot=len(data)
Training Data
val =
(maxid,user,year,month,fan,tubelight,television,refrigerator,washing_machine,microwave_ov
an,water_purifier,ac,water_heater,motor_pump,air_cooler,computer,electric_stove)
mycursor.execute(sql, val)
mydb.commit()
result="sucess"
fn=user+".csv"
writer.writerow(row)
70
with open('dataset/'+fn) as input, open('dataset/'+fn, 'w', newline='') as outfile:
writer.writerow(row)
Classification
##LSTM
amount_of_features = len(stock.columns)
sequence_length = seq_len + 1
result = []
result = np.array(result)
train = result[:int(row), :]
71
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], amount_of_features))
def build_model(layers):
model = Sequential()
model.add(LSTM(
input_dim=layers[0],
output_dim=layers[1],
return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(
layers[2],
return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(
output_dim=layers[2]))
model.add(Activation("linear"))
start = time.time()
model.compile(loss="mse", optimizer="rmsprop",metrics=['accuracy'])
return model
def build_model2(layers):
d = 0.2
model = Sequential()
72
model.add(LSTM(128, input_shape=(layers[1], layers[0]), return_sequences=True))
model.add(Dropout(d))
model.add(Dropout(d))
model.add(Dense(16,init='uniform',activation='relu'))
model.add(Dense(1,init='uniform',activation='linear'))
model.compile(loss='mse',optimizer='adam',metrics=['accuracy'])
return model
def classify():
msg=""
cnt=0
filename = 'upload/datafile.csv'
data2 = list(data1.values.flatten())
data=[]
data4=[]
i=0
sd=len(data1)
rows=len(data1.values)
ayr=[]
n=0
a=""
73
#print(str(sd)+" "+str(rows))
for ss in data1.values:
if a==ss[0]
if n==0:
ayr.append(a)
n+=1
else:
a=ss[0]
n=0
i+=1
#print(ayr)
cnt=len(ayr)
j=0
k=0
aa1=[]
data4=[]
# line 1 points
y1 = data5[0]
# line 2 points
74
x2 = [1,2,3]
y2 = data5[1]
# line 3 points
x3 = [1,2,3]
y3 = data5[2]
plt.xlabel('Home Appliances')
plt.ylabel('Energy Consumption')
plt.title('Yearwise Analysis')
plt.legend()
plt.show()
FORECASTING
arr_mn=[]
arr_x=[]
75
mycursor.execute("SELECT * FROM eb_data where uname=%s && month=%s &&
year!=%s",(uname,nmonth,yr))
data7 = mycursor.fetchall()
for ss in data7:
ss1=str(ss[3])+" "+str(ss[2])
arr_mn.append(ss1)
sm=ss[4]+ss[5]+ss[6]+ss[7]+ss[8]+ss[9]+ss[10]+ss[11]+ss[12]+ss[13]+ss[14]+ss[15]+ss[16]
smm=round(sm/13)
arr_x.append(smm)
av=0 nn=0
predict=0
for ax in arr_x:
av+=ax
nn+=1
if av>0:
predict=round(av/nn)
arr_x.append(predict)
cm=nmonth+" "+yr
arr_mn.append(cm)
dd2=arr_x
t=len(arr_mn)
dd1=arr_mn
print(dd1)
76
doc=[]
values=[]
ccc=['red','orange','yellow','green','brown','blue','pink','green','yellow','red','pink','blue','yellow'
]
c=[]
j=0
while j<t:
n2=randint(0,11)
ccc1=ccc[n2]
c.append(ccc1)
j+=1
#plt.ylim((1,g1))
plt.xlabel("Year")
plt.ylabel("Energy Consumption")
plt.title("")
fn="graph4.png"
plt.savefig('static/'+fn)
plt.close()
77
Set Limit
def set_limit():
data=""
msg=""
if 'username' in session:
uname = session['username']
f5=open("uname.txt","r")
uname=f5.read()
f5.close()
mycursor = mydb.cursor()
data = mycursor.fetchone()
if request.method=='POST':
limit=request.form['setlimit']
data1 = mycursor.fetchone()
mydb.commit()
Unit Calculation
def load_unit():
msg=""
78
uname=""
if 'username' in session:
uname = session['username']
f5=open("uname.txt","r")
uname=f5.read()
f5.close()
try:
yr=now.strftime("%Y")
mon=now.strftime("%m")
rdate=now.strftime("%d-%m-%Y")
uu=0
uu2=0
dd2=0
mycursor = mydb.cursor()
dd1 = mycursor.fetchall()
i=1
if rn1==i:
79
mydb.commit()
if rn2==i:
mydb.commit()
if rn3==i:
mydb.commit()
i+=1
dd = mycursor.fetchall()
for rr in dd:
dd2 = mycursor.fetchone()
unit=0.5
sec=rr[4]
if sec>0:
uu=sec/20
uu2=uu*unit
80
mydb.commit()
####
dcnt = mycursor.fetchone()[0]
if dcnt>0:
sn=0
su=0
# and status=1
sr11 = mycursor.fetchone()[0]
if sr11>0:
sr1 = mycursor.fetchall()
sn+=1
su+=0.25
if sn>0:
mydb.commit()
sec1=0.25
uu_unit=sec1*su
81
mycursor.execute("update eb_unit set unit=unit+%s where uname=%s &&
rdate=%s",(uu_unit,uname,rdate))
mydb.commit()
else:
maxid = mycursor.fetchone()[0]
if maxid is None:
maxid=1
val = (maxid,uname,'5','0',rdate,'0',mon,yr)
mycursor.execute(sql, val)
mydb.commit()
82
Appendix 2: Sample Screens
83
84
85
86
87
88
89
90
91
REFERENCES
1. Ricardo J. Bessa, Center for Power and Energy Systems, Solar Power Forecasting for
Smart Grids Considering ICT Constraints.
2. Huang, S.J. and K.R. Shih, 2003. Short term load forecasting via ARMA model ident
ificat ion including non- Gaussian process consideration. IEEE Trans. Power Syst ., 18:
673-679.
3. Kandil Nahi, Rene Wamkeue, Maarouf saad and Semaan Georges, 2006. An efficient
approach for short term load forecasting using artificial neural networks. Int. J. Electric
Power Energy system., 28: 525-530.
4. Mandal Paras, Tomonobu Senjyu, Naomitsu Urasaki, Toshihisa Funabashi, 2006. A
neural network based several hours ahead electric load forecast ing using similar days
approach. Int . J. Elect.
5. Topalli Ayca Kumluca, Ismet Erkmen and Ihsan Topalli, 2006.Intelligent short term load
forecast ing in Turkey. Int . J. Elect ric. Power Energy Syst., 28: 437- 447
6. Qingqing Mu , Yonggang Wu , Xiaoqiang Pan, Liangyi Huang,Xian Li Short-term Load
Forecasting Using Improved Similar Days Method 978-1-4244-4813- 5/10/$25.00 ©2010
IEEE
7. Jing-Min Wang and Li-Ping Wang, A new method for short-term electricity load
forecasting, Transactions of the Institute of Measurement and Control 30, 3/4 (2008) pp.
331–344.
8. Ruzic, A.Vuckovic, and N. Nikolic, “Weather Sensitive Method for Short-Term Load
Forecasting in Electric Power Utility of Serbia”, IEEE Transaction on Power Systems,
18:1581– 1586, 2003
9. T. Haida and S. Muto, “Regression Based Peak Load Forecasting using Transformation
Technique”. IEEE Transactions on Power Systems, 9:1788–1794, 1994.
10. W. Charytoniuk, M.S. Chen, and P. Van Olinda. “Nonparametric Regression Based
Short-Term Load Forecasting”, IEEE Transactions on Power Systems, 13:725–730, 1998.
11. Short term load forecasting using time series modelling with peak load estimation
capability”, IEEE Transactions on Power Systems, Vol.16, No.3 August 2001.
12. D.C. Park, M.A. El-Sharkawi, R.J. Marks II, L.E. Atlas & M.J. Damborg, "Electric load
forecasting using an artificial neural network", IEEE Transactions on Power Engineering,
vol.6, pp.442-449 (1991)
92
13. H. Mori and S. Tsuzuki, "Power System Topological Observability Analysis Using a
Neural Network Model," Proc. of 2nd Sym. on Expert Systems Application to Power
Systems, pp.385-391, July, 1989
14. M. S. Kandil, S. M. El-Debeiky, Senior Member, IEEE, and N. E. Hasanien , Long-Term
Load Forecasting for Fast Developing Utility Using a Knowledge- Based Expert System.
15. Mohamed Mohandes, Support vector machines for short-term electrical load forecasting
International Journal Of Energy Research Int. J. Energy Res. 2002; 26:335}345 (DOI:
10.1002/er.787)
Book References
1. "Python Flask Web Development" by Miguel Grinberg
2. "Flask Web Development: Developing Web Applications with Python" by Tarek Ziadé
and Philippe Makowski
3. "Python for Data Analysis" by Wes McKinney
4. "Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts,
Tools, and Techniques to Build Intelligent Systems" by Aurélien Géron
5. "MySQL Cookbook: Solutions for Database Developers and Administrators" by Paul
DuBois
Web References
1. Flask: http://flask.pocoo.org/
2. MySQL: https://www.mysql.com/
3. Flask-MySQL: https://flask-mysql.readthedocs.io/en/latest/
4. SQLAlchemy: https://www.sqlalchemy.org/
5. Jinja2: https://jinja.palletsprojects.com/en/3.0.x/
6. Bootstrap: https://getbootstrap.com/
7. jQuery: https://jquery.com/
8. Chart.js: https://www.chartjs.org/
9. Flask-RESTful: https://flask-restful.readthedocs.io/en/latest/
10.Flask-SocketIO: https://flask-socketio.readthedocs.io/en/latest/
93