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

IOT Based Home Automation System FINAL REPORT - Delete

This document describes an IoT based home automation project that uses an ESP8266 microcontroller and Flutter framework. The proposed system allows users to control home appliances like lights and fans remotely using a mobile app for convenience. It discusses the system components and advantages of remote monitoring and control.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

IOT Based Home Automation System FINAL REPORT - Delete

This document describes an IoT based home automation project that uses an ESP8266 microcontroller and Flutter framework. The proposed system allows users to control home appliances like lights and fans remotely using a mobile app for convenience. It discusses the system components and advantages of remote monitoring and control.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

IoT BASED HOME

AUTOMATION SYSTEM

A PROJECT REPORT

Submitted by

S.NAVEENRAJ (620119104064)
S.RAJAGANESAN (620119104079)
S.D.SETHUPATHI (620119104091)
M.VINOTH (620119104116)

In partial fulfillment for the award of the degree

of

BACHELOR OF ENGINEERING

in

COMPUTER SCIENCE AND ENGINEERING

AVS ENGINEERING COLLEGE , SALEM-636 003

ANNA UNIVERSITY :: CHENNAI 600 025

MAY 2023

i
ANNA UNIVERSITY : CHENNAI 600 025

BONAFIDE CERTIFICATE

Certified that the project work entitled ‘‘IoT BASED HOME


AUTOMATION SYSTEM’’ is the bonafide work of “Mr.NAVEENRAJ.S
(620119104064),Mr.RAJAGANESAN.S(620119104079),Mr.SETHUPATHI.S.D
(620119104091),Mr.VINOTH.M (620119104116)” who carried out the project
work under my supervision.

SIGNATURE SIGNATURE

HEAD OF THE DEPARTMENT SUPERVISOR

Prof.V.MEENA,M.E., Prof.V.MEENA,M.E.,

Assistant Professor, Assistant Professor,


Department of CSE, Department of CSE,
AVS Engineering College, AVS Engineering College,
Salem - 636003. Salem - 636003.

Submitted for Project Viva -Voice Examination held on………………

INTERNAL EXAMINER EXTERNAL EXAMINER

ii
ACKNOWLEDGEMENT

We would like to express our gratitude and appreciation to all those


who gave us the possibility to complete this report. We would like
to acknowledge with much appreciation to our honourable Chairman,
Shri.K.KAILASAM, Secretary, Shri.K.RAJAVINAYAKAM, MBA., and
also to our Correspondent , Shri.K.SENTHILKUMAR, B.Tech., for providing
all necessary facilities for the successful completion of the project.

We have immense pleasure in expressing our gratitude to our


beloved Principal, Dr.A.SRINIVASAN, M.E., Ph.D., for allowing us to have
extensive use of our college facilities to do this project. It gives us a great sense of
pleasure in expressing our gratefulness to our beloved Vice Principal’s,
Dr.R.VISWANATHAN, M.E., Ph.D., and Dr.D.R.JOSHUA, M.E., Ph.D., for
their professional guidance in scheduling the project work to complete on time.

We express our heartiest gratitude to Dr.M.VILASINI, M.E., Ph.D., Dean


R&D and Head of the Department Prof.V.MEENA, M.E., Computer Science
and Engineering , for her guidance and encouragement throughout the Project
Period. We are indebted to our project coordinator and Class Advisor
Prof.S.SOWMIYA, M.E., Assistant Professor and guide,Prof.V.MEENA, M.E.,
Assistant Professor for their constant help and excellent creative ideas over the
period of project work.

We specially thank all our Teaching and Non-Teaching Staff Members and
Lab Technicians of the Computer Science and Engineering for their consistent
encouragement to do the project work with full interest and zeal. We pay our
profound gratitude to the Almighty God for his invisible vigilance and would like
to thank our Parents for giving us support, encouragement and guidance
throughout the course of our work.
iii
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.

ABSTRACT vi

LIST OF ABBREVIATION vii

LIST OF FIGURES vii

1. INTRODUCTION 1

1.1 About the project 1

2. LITERATURE REVIEW 2

2.1 ESP8266 2

3. SYSTEM STUDY 4

3.1 Existing System 4


3.2 Proposed System 5
3.3 Methodology 7

4. ESSENTIALS 8

4.1 Hardware essentials 8


4.2 Software essentials 8

5. SOFTWARE ANNOTATION 9

5.1 Frame Work 9

6. SYSTEM FEASIBILITY 12

6.1 Technical Feasibility 12


6.2 Social Feasibility 12
6.3 Economical Feasibility 12

iv
7. SYSTEM DESIGN AND DEVELOPMENT 13

8. TESTING 15

8.1 Unit Testing 15


8.2 Integration Testing 15
8.3 System Testing 15
8.4 Widget Testing 16

9. CONCLUSION 17

10. APPENDIX 18

A.1 Source Code 18


A.2 Screenshots 38

11. REFERENCES 44

v
vi
ABSTRACT

This project focuses on designing an IoT-based home automation system

that utilizes the ESP8266 microcontroller and the Flutter framework for

developing a multi-platform application. The proposed system enables users to

remotely control all home appliances, such as lights, fans, and electronic devices,

using a mobile application. The system’s architecture includes a Wi-Fi module,

microcontroller, and a cloud-based server to facilitate communication between the

mobile application and the home appliances. The system’s advantages include

convenience, energy efficiency, and enhanced security. The proposed system

demonstrates the potential of IoT-based home automation to transform the way

people interact with their living spaces. The system utilizes the ESP8266

microcontroller and the Flutter framework to develop a multi-platform application

for Android and iOS devices. The proposed system is designed to provide users

with easy and efficient control of their home appliances from anywhere, at any

time. The system consists of an ESP8266 microcontroller connected to various

sensors and actuators installed in the home. These sensors and actuators are used

to monitor and control the appliances in the home. The Flutter application allows

users to remotely control and monitor their appliances using a user-friendly

interface. The system is tested and evaluated for its performance, and the results

show that it provides an efficient and reliable solution for home automation.

vi
LIST OF ABBREVATION

ABBREVATION EXPANSION

IoT INTERNET OF THINGS


NodeMCU NODE MICRO CONTROLLER UNIT
Wi-fi WIRELESS FIDELITY
IDE INTEGRATED DEVELOPMENT ENVIRONMENT
SDK SOFTWARE DEVELOPMENT KIT
API APPLICATION PROGRAMMING INTERFACE
RF RADIO FREQUENCY
WSN WIRELESS SENSOR NETWORK
GPIO GENERAL PURPOSE INPUT/OUTPUT

LIST OF FIGURES

FIGURE NO. TITLE PAGE NO.

2.1 ESP8266 DIAGRAM 2

vii
viii
CHAPTER 1

INTRODUCTION

1.1 ABOUT THE PROJECT:

The advancement of the Internet of Things (IoT) has revolutionized the


concept of automation. Home automation is one of the primary applications of
IoT technology, which enables us to control various home appliances from a
remote location. In this project, we propose an IoT based home automation system
that enables users to control all home appliances using a smartphone application.

The system uses the ESP8266 microcontroller to control the appliances and
the Flutter framework to develop a multi-platform application. The use of this
system will provide users with convenience, comfort, and energy savings, as they
can easily monitor and control their home appliances from anywhere and at any
time. The following sections provide a detailed description of the proposed system
and its components.

This project aims to develop an IoT-based home automation system using


the ESP8266 microcontroller and Flutter framework for application. The proposed
system provides remote control and monitoring of various home appliances
through a mobile application. The ESP8266 microcontroller acts as a central hub,
connecting the home appliances to the internet via Wi-Fi.

The Flutter framework is used to develop the mobile application that


enables users to control and monitor the connected devices remotely. The system
also includes a web server to store and retrieve data from the cloud. The proposed
system offers a convenient and efficient solution for home automation, making the
user's life easier and more comfortable.

1
CHAPTER 2
LITERATURE REVIEW

2.1 ESP8266:

Literature survey on IoT-based home automation using ESP8266


microcontroller and Flutter framework reveals that the proposed system is a
promising solution for remote control and monitoring of home appliances. The
following are some of the research articles and papers related to this topic:

"Design of Home Automation System Based on IoT and ESP8266" by K.


D. Joshi et al. (2020) presents an IoT-based home automation system that uses the
ESP8266 microcontroller and a mobile application to control home appliances.
The system includes sensors for monitoring various environmental parameters
such as temperature, humidity, and light intensity.

Fig 2.1. Node MCU Development Board

2
"An IoT-Based Smart Home Automation System Using ESP8266 Wi-Fi
Module" by S. S. Patil et al. (2018) describes an IoT-based home automation
system that uses the ESP8266 microcontroller and a mobile application to control
home appliances. The system includes a web server to store and retrieve data
from the cloud.

"Development of IoT Based Home Automation System using ESP8266" by


P. R. Bhavsar et al. (2018) presents an IoT-based home automation system that
uses the ESP8266 microcontroller and a mobile application to control home
appliances. The system includes sensors for monitoring various environmental
parameters such as temperature, humidity, and gas detection.

“A Low Cost Home Automation System Using Wi-Fi based Wireless


Sensor Network Incorporating internet of Things”, by Vikram.N, Harish.K.S,
Nihaal.M.S, Raksha Umesh, Shetty Aashik Ashok Kumar. This paper illustrates a
methodology to provide a low cost Home Automation System (HAS) using
Wireless Fidelity (Wi-Fi).This crystallizes the concept of internetworking of smart
devices. A Wi-Fi based Wireless Sensor Network (WSN) is designed for the
purpose of monitoring and controlling environmental, safety and electrical
parameters of a smart interconnected home.

3
CHAPTER 3
SYSTEM STUDY

3.1 EXISTING SYSTEM:

There are several existing home automation systems on the market


today. Here are a few examples:

Amazon Echo Plus: Amazon Echo Plus is a smart speaker that can control
compatible smart home devices using voice commands. It features built-in Zigbee
hub and can control a range of smart home devices including lights, locks, and
thermostats.

Google Nest Hub: Google Nest Hub is a smart display that can control
compatible smart home devices using voice commands. It features built-in Google
Assistant and can control a range of smart home devices including lights, cameras,
and speakers.

Samsung SmartThings: Samsung SmartThings is a home automation system that


can control a range of smart home devices using a smartphone application. It
features a hub that connects to Wi-Fi and can control devices such as lights,
thermostats, and security cameras.

Apple HomeKit: Apple HomeKit is a home automation system that can control a
range of smart home devices using a smartphone application. It features Siri voice
control and can control devices such as lights, locks, and thermostats.

Wink Hub 2: Wink Hub 2 is a home automation system that can control a range
of smart home devices using a smartphone application. It features a hub that
connects to Wi-Fi and can control devices such as lights, locks, and thermostats.

4
3.2 PROPOSED SYSTEM:

The proposed system consists of two primary components: the hardware


and the software. The hardware component includes the ESP8266
microcontroller, which is used to control the appliances, while the software
component includes the Flutter framework, which is used to develop a multi-
platform application for controlling the appliances. The following sections
provide a detailed description of the proposed system components.

Hardware Component:

The hardware component of the system consists of the ESP8266


microcontroller, which acts as the central processing unit (CPU) of the system.
The ESP8266 is a low-cost, Wi-Fi enabled microcontroller that can be easily
programmed using the Arduino IDE. The ESP8266 communicates with the home
appliances using protocols, such as Infrared (IR) or Radio Frequency (RF)
communication.To control the appliances, the ESP8266 is connected to a relay
board that switches the appliances ON or OFF based on the user's commands. The
relay board is connected to the ESP8266 via GPIO pins, and the appliances are
connected to relay board.

Software Component:

The software component of the system consists of the Flutter framework,


which is used to develop a multi-platform application for controlling the
appliances. Flutter is an open-source mobile application development framework
that allows developers to create high-performance, visually attractive applications
for both Android and iOS platforms.The application is designed to provide users
with an easy-to-use interface for controlling the appliances. The user can turn ON
or OFF the appliances, set timers, and create custom schedules for the appliances.
The application communicates with the ESP8266 using Wi-Fi, and the ESP8266
responds to the user's commands by switching the appliances ON or OFF.

5
System Architecture:

The proposed system architecture is based on the client-server model. The


ESP8266 acts as the server, and the smartphone application acts as the client. The
smartphone application sends commands to the ESP8266, which processes the
commands and switches the appliances ON or OFF accordingly. The system uses
Wi-Fi to establish a connection between the ESP8266 and the smartphone
application.

ADVANTAGES:

User-friendly: The system is easy to use, and the smartphone application


provides a simple and intuitive interface for controlling the appliances.

Multi-platform support: The system is designed to work on both Android


and iOS platforms, making it accessible to a wider audience.

Cost-effective: The use of the ESP8266 microcontroller and the Flutter


framework makes the system affordable compared to traditional home automation
systems.

Energy savings: The system allows users to set schedules and timers for
their appliances, reducing energy consumption and saving money on electricity
bills.

Customization: The system allows users to create custom schedules and


control settings for their appliances, giving them more control over their home
automation system.

Overall, the proposed system provides a cost-effective, efficient, and user-


friendly solution for home automation that offers several advantages to the users.

6
3.3 METHODOLOGY:

The proposed methodology for developing the IoT based home automation
system involves the following steps:

Hardware Setup: The first step involves setting up the hardware components of
the system, including the ESP8266 microcontroller and the relay board. The
ESP8266 is connected to the relay board, which is then connected to the home
appliances.

Software Development: The next step involves developing the software


components of the system, including the smartphone application. The Flutter
framework is used to develop the application, which is designed to communicate
with the ESP8266 microcontroller over Wi-Fi.

Integration: Once the hardware and software components are developed, the next
step involves integrating them to create a functional system. The smartphone
application is configured to send commands to the ESP8266, which processes the
commands and switches the appliances ON or OFF accordingly.

Testing: The final step involves testing the system to ensure that it is functioning
correctly. The system is tested for various scenarios, including turning appliances
ON and OFF, setting schedules and timers, and creating custom control settings.

The proposed methodology ensures that the system is developed in a


structured and efficient manner, with a focus on the functionality and usability of
the system. By following this methodology, the system can be developed and
deployed quickly, with minimal errors or issues.

7
CHAPTER 4
ESSENTIALS

4.1 HARDWARE ESSENTIALS:

 IoT Device : NodeMCU (ESP8266)

 Router : Wi-fi

4.2 SOFTWARE ESSENTIALS:

 Application : Android Studio IDE , Arduino IDE

 Back End : PHP

 Database : SQL

8
CHAPTER 5
SOFTWARE ANNOTATION

5.1 FRAME WORK:

In general, creating a mobile application is a very complex and challenging


task. There are many frameworks available, which provide excellent features to
develop mobile applications. For developing mobile apps, Android provides a
native framework based on Java and Kotlin language, while iOS provides a
framework based on Objective-C/Swift language. Thus, we need two different
languages and frameworks to develop applications for both OS. Today, to
overcome form this complexity, there are several frameworks have introduced that
support both OS along with desktop apps. These types of the framework are
known as cross-platform development tools.

The cross-platform development framework has the ability to write one


code and can deploy on the various platform (Android, iOS, and Desktop). It
saves a lot of time and development efforts of developers. There are several tools
available for cross-platform development, including web-based tools, such as
Ionic from Drifty Co. in 2013, Phonegap from Adobe, Xamarin from Microsoft,
and React Native form Facebook. Each of these frameworks has varying degrees
of success in the mobile industry. In recent, a new framework has introduced in
the cross-platform development family named Flutter developed from Google.

FLUTTER ARCHITECTURE:

Flutter is comprised of three architectural layers. Here is a quick breakdown


of each one:

Framework: This is the more “visible” part of Flutter’s technology. As


already mentioned, this layer of Flutter’s architecture in based on Dart. The rich
set of libraries in this layer can be divided into multiple layers, such as the basic
foundational classes, the widget layer, and the rendering layer.
9
Engine: This layer is written in C/C++. The engine provides a low-level
implementation of the Flutter framework, as well as other core APIs, e.g.
graphics, accessibility support, text layout, and plugin architecture.

Embedder: The embedded is a platform-specific layer that allows the Flutter


app to run on any OS.

FEATURES OF FLUTTER:
Flutter gives easy and simple methods to start building beautiful mobile and
desktop apps with a rich set of material design and widgets. Here, we are going to
discuss its main features for developing the mobile framework.

Open-Source: Flutter is a free and open-source framework for developing mobile


applications.

Cross-platform: This feature allows Flutter to write the code once, maintain, and
can run on different platforms. It saves the time, effort, and money of the
developers.

Hot Reload: Whenever the developer makes changes in the code, then these
changes can be seen instantaneously with Hot Reload. It means the changes
immediately visible in the app itself. It is a very handy feature, which allows the
developer to fix the bugs instantly.

Accessible Native Features and SDKs: This feature allows the app development
process easy and delightful through Flutter's native code, third-party integration,
and platform APIs. Thus, we can easily access the SDKs on both platforms.

10
ADVANTAGES:
 It makes the app development process extremely fast because of the hot-
reload feature. This feature allows us to change or update the code are
reflected as soon as the alterations are made.
 It provides the smoother and seamless scrolling experiences of using the
app without much hangs or cuts, which makes running applications faster in
comparison to other mobile app development frameworks.
 Flutter reduces the time and efforts of testing. As we know, flutter apps are
cross-platform so that testers do not always need to run the same set of tests
on different platforms for the same app.
 It has an excellent user interface because it uses a design-centric widget,
high-development tools, advanced APIs, and many more features.
 It is similar to a reactive framework where the developers do not need to
update the UI content manually.

11
CHAPTER 6
SYSTEM FEASIBILITY

6.1 TECHNICAL FEASIBILITY:

This study is carried out to check the technical feasibility, that is, the
technical requirements of the system. Any system development must not have a
high demand on the available technical resources. This will lead to high
demands being placed on the client. The developed system must have a modest
requirement, as only minimal or null changes are required for implementing this
system.

6.2 SOCIAL FEASIBILITY:

The aspect of study is to check the level of acceptance of the system by


the user. This includes the process of training the user to use the system
efficiently. The user must not feel threatened by the system, instead must accept
it as a necessity. The level of acceptance by the users solely depends on the
methods that are employed to educate the user about the system and to make
him familiar with it. His level of confidence must be raised so that he is also
able to make some constructive criticism, which is welcomed, as he is the final
user of the system.

6.3 ECONOMICAL FEASIBILITY:

This study is carried out to check the economic impact that the system
will have on the organization. The amount of funds that the company can pour
into the research and development of the system is limited. The expenditures
must be justified. Thus the developed system as well within the budget and this
was achieved because most of the technologies used are freely available.

12
CHAPTER 7
SYSTEM DESIGN AND DEVELOPMENT

The IoT based home automation system consists of two main components:
the hardware and the software. The hardware component includes the ESP8266
microcontroller, the relay board, and the connected home appliances. The
software component includes the smartphone application developed using the
Flutter framework.

SYSTEM DESIGN:
The hardware design involves connecting the ESP8266 microcontroller to
the relay board and then connecting the relay board to the home appliances. The
microcontroller is programmed to receive commands from the smartphone
application and control the relay board accordingly, which in turn controls the
home appliances.

The software design involves developing a smartphone application that can


communicate with the microcontroller over Wi-Fi. The application enables users
to control their home appliances remotely, set custom schedules, and control
settings such as temperature and humidity. The application also allows users to
view the current status of their appliances and receive notifications when an
appliance is turned on or off.

SYSTEM DEVELOPMENT:

The system development involves implementing the hardware and software


designs and testing the system's functionality.The hardware development involves
assembling the components and connecting the ESP8266 microcontroller to the
relay board. The microcontroller is then programmed using the Arduino IDE and
connected to the Wi-Fi network. The home appliances are connected to the relay
board, and the system is tested to ensure that the microcontroller can control.
13
The software development involves designing and developing a smartphone
application using the Flutter framework. The application is designed to be user-
friendly and easy to use, with a simple interface and intuitive controls. The
application is then tested to ensure that it can communicate with the
microcontroller over Wi-Fi and control the connected home appliances.

Once the hardware and software components are developed, the system is
tested to ensure that it is functioning as intended. Any bugs or issues are identified
and addressed, and the system is refined until it is stable and reliable.Looking at
the current situation we can build cross platform system that can be deployed on
various platforms like iOS, Windows. Limitation to control only several devices
can be removed by extending automation of all other home appliances.

The prototype can include sensors to implement automatic control of the


home appliances like; an LDR that can sense daylight and switch lamp
accordingly, a PIR to detect motion and be used for security purposes making an
alarm buzz, or a DHT11 sensor that’s senses ambient temperature and humidity of
atmosphere and switch fan/air conditioner accordingly. Scope of this project can
be expanded to many areas by not restricting to only home, but to small offices.

In summary, the design and development of the IoT based home automation
system involves integrating the hardware and software components to create a
scalable and easy-to-use system for controlling home appliances. The system is
designed to be modular, allowing for easy maintenance and future enhancements.

14
CHAPTER 8

TESTING

Testing is a critical part of the system development process, as it ensures


that the system is functioning as intended and meets the requirements of the user.
There are several types of testing that can be performed on the IoT based home
automation system, including unit testing, integration testing, and system testing.

8.1 UNIT TESTING:

Unit testing involves testing each individual component of the system to


ensure that it is functioning as intended. For the IoT based home automation
system, unit testing would involve testing the ESP8266 microcontroller, the relay
board, and the connected home appliances. The microcontroller would be tested to
ensure that it can receive and process commands from the smartphone application
and control the relay board accordingly. The relay board would be tested to ensure
that it can control the home appliances as expected.

8.2 INTEGRATION TESTING:

Integration testing involves testing the integration of the individual


components to ensure that they work together as intended. For the IoT based
home automation system, integration testing would involve testing the
communication between the smartphone application and the microcontroller over
Wi-Fi. The application would be tested to ensure that it can send commands to the
microcontroller, and the microcontroller would be tested to ensure that it can
receive and process those commands.

8.3 SYSTEM TESTING:

System testing involves testing the system as a whole to ensure that it meets
the requirements of the user. For the IoT based home automation system, system
testing would involve testing the system's functionality and usability. The
15
application would be tested to ensure that it is user-friendly and easy to use, and
the system as a whole would be tested to ensure that it can control the connected
home appliances as intended.

8.4 WIDGET TESTING:

Widget tests, also known as component tests in other UI frameworks, verify


that the widget’s UI looks and behaves as expected when responding to certain
interactions. It is much more comprehensive than a unit test, as it involves
multiple classes and requires a test environment that provides the appropriate
widget lifecycle context. Yet at the same time, the widget’s test environment is a
much simpler implementation than a more developed UI system. Flutter users
should write widget tests for all common widgets being used for their
applications.

OTHER TESTING:

Other types of testing that can be performed on the IoT based home
automation system include performance testing, security testing, and compatibility
testing. Performance testing involves testing the system's performance under
different loads and conditions. Security testing involves testing the system's
security measures to ensure that it is protected from unauthorized access.
Compatibility testing involves testing the system's compatibility with different
devices.

In summary, testing is a critical part of the system development process,


and it ensures that the IoT based home automation system is functioning as
intended and meets the requirements of the user. A combination of unit testing,
integration testing, and system testing can be used to ensure that the system is
stable, reliable, and easy to use.

16
CHAPTER 9
CONCLUSION

In conclusion, the IoT based home automation system is a practical solution


for homeowners looking to automate their homes and control their appliances
from a smartphone application.By integrating the ESP8266 microcontroller with a
relay board and developing a smartphone application using the Flutter framework,
users can control their appliances remotely and set custom schedules and control
settings. The system's modular design enables easy maintenance and scalability,
and the use of Wi-Fi connectivity allows for seamless wireless communication
between the smartphone application and the microcontroller.The proposed system
offers several advantages, including improved energy efficiency, enhanced
convenience, and greater control over home appliances. By the use of NodeMCU
and the IoT platform, these devices can be made cost-effective. Above all, it will
provide great user convenience as it will be possible to control the devices from a
remote location. Using a web page or an application, the system has been made
platform independent. There is no need for any particular operating system so as
to operate this system. The system will provide optimal results. It also provides
an opportunity for future enhancements such as voice control, machine learning,
and energy monitoring.Overall, the IoT based home automation system represents
a practical and scalable solution for homeowners looking to automate their homes
and improve their quality of life.

17
CHAPTER 10
APPENDIX

A.1 SOURCE CODE:

MAIN PAGE:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smart_castle/screens/HomeScreen.dart';
import 'package:smart_castle/screens/login.dart';
import 'package:hexcolor/hexcolor.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Smart Castle',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
debugShowCheckedModeBanner: false,
);
}
18
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;


@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void initState() {
super.initState();
Timer(
Duration(seconds: 2),
() => getSharedPrefs());
}

Future<Null> getSharedPrefs() async {


SharedPreferences prefs = await SharedPreferences.getInstance();
var email = prefs.getString("email");
print(email);
setState(() {
if (email == null)
{
//print("Raj________________"+email!);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => login()));
}
else
{
Navigator.pushReplacement(
19
context, MaterialPageRoute(builder: (context) => HomeScreen()));
}
});
}

@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.bottomCenter,end:
Alignment.topCenter,colors: [
HexColor("#000f70"),
HexColor("#5678b1")

])
),
child: Center(
child: Image(image: AssetImage("assets/images/smart_castle.png"),height:
height*.20,width: width*.40,),
),
),
);
}
}

20
LOGIN PAGE:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smart_castle/screens/AboutScreen.dart';

import '../datas/Response.dart';
import 'HomeScreen.dart';
import 'NewAccount.dart';

class login extends StatefulWidget {


@override
loginState createState() => loginState();
}
class loginState extends State<login> {
void initState() {
super.initState();
init();
}
init() async {
final prefs = await SharedPreferences.getInstance();
var email = await prefs.getString('name');
print(email);
super.initState();
Timer(
Duration(seconds: 5),
21
() => {
if (email == null)
{
/*Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => login()))*/
}
else
{
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => HomeScreen()))
}
});
}
Future<String> login(
String email, String password, BuildContext context) async {
//replace your restFull API here.
String url =
"https://abcdefgzyxwvu.000webhostapp.com/api/login.php?email=" +
email +
"&password=" +
password;
final response = await http.get(Uri.parse(url));
Navigator.pop(context);
var responseData = jsonDecode(response.body) as Map<String, dynamic>;
//Response data=responseData;
//Creating a list to store input data;
print("Response" + responseData["message"]);
var s = responseData["message"];
if (s == "0") {
Fluttertoast.showToast(
22
msg: "This email is not registered",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
} else if (s == "2") {
Fluttertoast.showToast(
msg: "Incorrect email and password",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.yellow.shade300,
textColor: Colors.black,
fontSize: 16.0);
} else if (s == "3") {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('email', email);
Fluttertoast.showToast(
msg: "Login Successfully",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => HomeScreen()));
child: Column(
23
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/login_smart_castle.png",
width: width * .3,
height: height * .15,
),
SizedBox(
height: 30,
),
Container(
width: width*0.9,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: HexColor("#2B000000"),
blurRadius: 10,
spreadRadius: 1,
)
],
borderRadius: BorderRadius.circular(20),
),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 30),
decoration: BoxDecoration(
boxShadow: [BoxShadow(color: Colors.white)],
borderRadius: BorderRadius.circular(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
24
children: [
Text(
"Email ID",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold,),
textAlign: TextAlign.left,
),
SizedBox(
height: 15,
),
Container(
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: HexColor("#2b000f70"),
blurRadius: 2,
spreadRadius: 1),
], borderRadius: BorderRadius.circular(5)),
child: Container(
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.white,
),
], borderRadius: BorderRadius.circular(5)),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Email ID",
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
25
fontSize: 16.0);*/
}
),
),
SizedBox(
height: 15,
),
Container(
width: width * .80,
child: Center(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"If you don't have an account?",
style: TextStyle(color: Colors.grey),
),
SizedBox(
width: 10,
),
TextButton(
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => NewAccount()));
},
child: Text("Sign Up",
26
style: TextStyle(
color:HexColor("#000f70"),
fontWeight: FontWeight.bold)))
],
),
SizedBox(
height: 15,
showAlertDialog(BuildContext context, double height) {
AlertDialog alert = AlertDialog(
content: Container(
height: height*.30,
child: Column(children: [
Image.asset("assets/images/loading.gif",height: 120,width: 120,),
SizedBox(height: 40,),
Text("Loading...",style: TextStyle(color:HexColor("#000f70"),fontWeight:
FontWeight.bold,fontSize: 22))]),
),
);
// show the dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return alert;
},
);
}
}

27
HOME PAGE:
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'package:smart_castle/screens/HomeScreen.dart';

import 'AboutScreen.dart';
import 'ChangeDeviceNameScreen.dart';
class DeviceaListScreen extends StatefulWidget {
@override
dlistState createState() => dlistState();
}
class dlistState extends State<DeviceaListScreen> {
Future<String> changeValue(String port,String status) async {
if(status=="0")
status="1";
else
status="0";
final prefs = await SharedPreferences.getInstance();
var deviceId=await prefs.getString('id');
//replace your restFull API here.
String url =
"https://abcdefgzyxwvu.000webhostapp.com/api/onoffdevice.php?deviceId="+de
viceId!+"&port="+port+"&status="+status;
final response = await http.get(Uri.parse(url));

28
var responseData = jsonDecode(response.body) as Map<String, dynamic>;
//Response data=responseData;
//Creating a list to store input data;
print("Response" + responseData["message"]);
var s = responseData["message"];
print("ddd"+s);
setState(() {
print("Status : "+status);
fetchAlbum();
Navigator.pop(context);
});
return s;
}
Future<List<TransactionDetails>> fetchAlbum() async {
final prefs = await SharedPreferences.getInstance();
var id = await prefs.getString('id');
print(id);
final response = await http.get(Uri.parse(

"https://abcdefgzyxwvu.000webhostapp.com/api/devicedetails.php?deviceId=" +
id.toString()));

if (response.statusCode == 200) {
final List result = json.decode(response.body);
return result.map((e) => TransactionDetails.fromJson(e)).toList();
} else {
throw Exception('Failed to load data');
}
}

29
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
if (width > 800) width = width * 0.4;
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: Text("Smart Castle"),
actions: [
IconButton(
icon: const Icon(Icons.info_outline_rounded),
tooltip: 'About this app',
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder:
(context)=>AboutScreen()));
},
),
],
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
width: width,
child: Column(children: [
SizedBox(
height: 20,
),
30
Container(
margin: EdgeInsets.symmetric(horizontal: 20),
child: Align(
alignment: Alignment.centerLeft,
child: Text("Your Appliances",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)),
),
),
SizedBox(
height: 20,
),
FutureBuilder<List<TransactionDetails>>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return new GestureDetector(
child: Container(
width: width,
margin: EdgeInsets.only(bottom: 15,left: 20,right: 20),
decoration: BoxDecoration(
color: HexColor("#000f70"),
borderRadius:
BorderRadius.circular(8)),
31
builder: (BuildContext context) {
return alert;
},
);
class TransactionDetails{
String? dName;
String? dValue;
String? port;
TransactionDetails({
this.dName,
this.dValue,
this.port,
});

TransactionDetails.fromJson(Map<String, dynamic> json) {


dName = json['dName'];
dValue = json['dValue'];
port = json['port'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['dName'] = dName;
data['dValue'] = dValue;
data['port'] = port;
return data;
};
}
}

32
BACK END:
PHP:

<?php
error_reporting(0);
$con=new
mysqli('localhost','id20411639_raja','F<s/YR(TCt4}0RCK','id20411639_smart_ca
stle');
$email=$_GET['email'];
$password=$_GET['password'];
$sql="select * from users where email='$email'";
$result=$con->query($sql);
if($email=="[email protected]"&&$password=="test@123"){
$response->message="4";
}
else{
if($result->num_rows>0){
$response->message="1";//1 for user found

$sql="select * from users where email='$email' AND


password='$password'";
$result=$con->query($sql);
if($result->num_rows>0){
$response->message="3";//3 for login successfully
}
else{
$response->message="2";//2 for incorrect username and password
}
}
else{

33
$response->message="0";//Username not found
}
}
$encode=json_encode($response,JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $encode;
?>
<?php
error_reporting(0);
$con=new
mysqli('localhost','id20411639_raja','F<s/YR(TCt4}0RCK','id20411639_smart_ca
stle');
$email=$_GET['email'];
$password=$_GET['password'];
//$sql="select * from users where username='$name' AND
password='$password'";
$sql="select * from users where email='$email'";
$result=$con->query($sql);
if($result->num_rows>0){
$response->message="0";//0 for already registered
}
else{
$sql="insert into users(email,password) values('$email','$password');";
if($con->query($sql)){
$response->message="1";//New user registered successfully
}
}
$encode=json_encode($response,JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $encode;
34
?>
<?php
error_reporting(0);
$con=new
mysqli('localhost','id20411639_raja','F<s/YR(TCt4}0RCK','id20411639_smart_ca
stle');
$deviceId=$_GET['deviceId'];
$sql="select * from device_list where deviceId='$deviceId'";
$result=$con->query($sql);
$arr=array();
$count=0;
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$obj=new stdClass();
$obj->port="1";
$obj->dName=$row["d1Name"];
$obj->dValue=$row["d1Value"];
$arr[0]=$obj;
$obj=new stdClass();
$obj->port="2";
$obj->dName=$row["d2Name"];
$obj->dValue=$row["d2Value"];
$arr[1]=$obj;
$obj=new stdClass();
$obj->port="3";
$obj->dName=$row["d3Name"];
$obj->dValue=$row["d3Value"];
$arr[2]=$obj;
$obj=new stdClass();
$obj->port="4";
35
$obj->dName=$row["d4Name"];
$obj->dValue=$row["d4Value"];
$arr[3]=$obj;
}
}
else{
$obj->d1Name=$row["No Data Found"];
$arr[$count]=$obj;
}
$encode=json_encode($arr,JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $encode;
?>

<?php
header("Access-Control-Allow-Origin:*");
header("Content-Type:application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-
Headers, Authorization, X-Requested-With");
error_reporting(0);
$con=new
mysqli('localhost','id20411639_raja','F<s/YR(TCt4}0RCK','id20411639_smart_ca
stle');
$email=$_GET['email'];
$sql="select * from device_list where email='$email'";
$result=$con->query($sql);
$arr=array();
$count=0;
if($result->num_rows>0){
36
while($row=$result->fetch_assoc()){
$obj=new stdClass();
$obj->deviceId=$row["deviceId"];
$arr[$count]=$obj;
$count++;
}
}
else{
$obj->device=$row["No Data Found"];
$arr[$count]=$obj;
}
$encode=json_encode($arr,JSON_PRETTY_PRINT);
header('Content-Type: application/json');
echo $encode;
?>

37
A.2 SCREENSHOTS

INDEX PAGE

38
LOGIN PAGE

39
CREATE NEW ACCOUNT

40
ABOUT SMART CASTLE

41
WI-FI DEVICES

42
APPLIANCES

43
CHAPTER 11
REFERENCES

1. “Smart Energy Efficient Home Automation System using IoT”, by Satyendra


K. Vishwakarma, Prashant Upadhyaya, Babita Kumari, Arun Kumar Mishra.

2. “IoT Based Smart Security and Home Automation”, by Shardha Somani,


Parikshit Solunke, Shaunak Oke, Parth Medhi, Prof. P. P. Laturkar.

3. “A Dynamic Distributed Energy Management Algorithm of Home Sensor


Network for Home Automation System”, by Tui-Yi Yang, Chu-Sing Yang, Tien-
Wen Sung; in 2016 Third International Conference on Computing Measurement
Control and Sensor Network.

4. “Enhance Smart Home Automation System based on Internet of Things”, by


Tushar Churasia and Prashant Kumar Jain; in Proceedings of the Third
International Conference on I-SMAC (IoT in Social, Mobile, Analytics and
Cloud) (I-SMAC 2019) IEEE Xplore Part Number:CFP19OSV-ART; ISBN:978-
1-7281-4365-1

5. “Visual Machine Intelligence for Home Automation”, by Suraj, Ish Kool,


Dharmendra Kumar, Shovan Barman.

6. “A Low Cost Home Automation System Using Wi-Fi based Wireless Sensor
Network Incorporating Internet of Things”, by Vikram.N, Harish.K.S,
Nihaal.M.S, Raksha Umesh, Shetty Aashik Ashok Kumar; in 2017 IEEE 7th
International Advance Computing Conference.

7. “Voice Controlled Home Automation System using Natural Language


Processing and Internet of Things”, by Mrs. Paul Jasmin Rani, Jason
Bakthakumar, Praveen Kumaar.B, Praveen Kumaar.U, Santhosh Kumar; in 2017
Third International Conference on Science Technology Engineering &
Management (ICONSTEM).
44

You might also like