0% found this document useful (0 votes)
95 views118 pages

Iot Platform For Home Automation

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

Iot Platform For Home Automation

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

University of Benghazi

Faculty of Information Technology


Computer Networks & Communication Department

IOT PLATFORM FOR HOME AUTOMATION

A Project submitted in partial fulfillment of the requirements for the degree of


Bachelor of Science (B.Sc.) in Computer Networks & Communications.

By

Malak Khalid Boujanah (3571)


Fatima Marae EL-Gheryani (3442)
Marwa Salah El-Shareef (3016)

Supervisors
Mr. Khalid Ateea EL-Faitouri

Autumn 2021/2022
‫جـــامــعـة بـــنــغـــازي‬
‫كــلـية تـقـــنـيـة المـعــلـومــات‬
‫قسم شبكات و اتصالات الحاسوب‬

‫‪IOT PLATFORM FOR HOME AUTOMATION‬‬

‫قــدّم مـشـــروع التــخـرج هــذا كجــزء مـن متــطـلـبات الحــصـول عـلـى درجة البــكـالــوريــوس فــي‬
‫صص شـبــكـات و اتـصـاالت الحــاســوب‬
‫تـخـــ ّ‬

‫مقدّم من قبل‬

‫(‪)3571‬‬ ‫مالك خالد بوجناح‬


‫(‪)3442‬‬ ‫فاطمة مرعي الغرياني‬
‫(‪)3016‬‬ ‫مروة صالح الشريف‬

‫تحت إشراف‬
‫أ‪ .‬خالد عطية الفيتوري‬

‫خريف ‪2022/2021‬‬
Copyrights © 2022.

All rights reserved, no part of this project work may be reproduced in any
form, or by any means, without the permission in writing from the author(s) and the
department of Computer Networks & Communications, Faculty of IT, University of
Benghazi.
The project entitled:

IOT PLATFORM FOR HOME


AUTOMATION
Which is being submitted by

Malak Khalid Boujanah (3571)


Fatima Marae EL-Gheryani (3442)
Marwa Salah El-Shareef (3016)

In the partial fulfillment of requirements for the award of the B.Sc.


degree in Computer Networks & Communications, has been carried out under
my supervision, and accepted for presentation and examination.

Signature :

Mr. Khalid Ateea EL-Faitouri


Date: / / 20__
1st Supervisor

Signature :

Prof./Dr./Mr./Ms./Mrs. ________________
Date: / / 20__
2nd Supervisor
The project entitled:

IOT PLATFORM FOR HOME


AUTOMATION
Which is being submitted by

Malak Khalid Boujanah (3571)


Fatima Marae EL-Gheryani (3442)
Marwa Salah El-Shareef (3016)

In the partial fulfillment of requirements for the award of the B.Sc.


degree in Computer Networks & Communications, has been examined by us
and all our recommendations during the discussion/examination have been
carried out. The project report has been accepted in the Autumn Semester of
the Academic Year 2021/2022.

1st Examiner ( The Supervisor ) 2nd Examiner


Signature : Signature:

Name : Name :
Date: / / 20__ Date: / / 20__

3rd Examiner
Signature:

Name :
Date: / / 20__
Abbreviations

Abbreviations

AES Advanced Encryption Standard

API Application Programming Interface

AQI Air Quality Index

ARM Advanced RISC Machines

ASK Amplitude Shift Keying

BFSK Binary Frequency shift keying

BLE Bluetooth Low Energy

BPSK Binary Phase Shift Keying

COM Common

CPU Central Processing Unit

CSS Chirp Spread Spectrum

CSS Cascading Style Sheets

CSV Comma-Separated Values

DBPSK Differential Binary Phase-Shift Keying

DHT11 Temperature-Humidity Sensor

DPSK Differential Phase Shift Keying

DQPSK Differential Quadrature Phase Shift Keying

ETSI European Telecommunications Standards Institute

I
Abbreviations

GFSK Gaussian frequency-shift keying

GND Ground

GPIOs General Purpose Input/Output pins

GSM Global System for Mobile Communications

GSMA Global System for Mobile Communications Association

GUI Graphical User Interface

HA Home Automation

HTML Hyper Text Markup Language

HTTP Hypertext Transfer Protocol

IaaS Infrastructure as a Service

IANA Internet Assigned Numbers Authority

IBM International Business Machines

IDE Integrated Development Environment

IEC International Electrotechnical Commission

IEEE Institute of Electrical and Electronics Engineers

IFTTT If This Then That

IoT Internet of Things

IP Internet Protocol

ISM Industrial, Scientific, and Medical

ISO International Organization for Standardization

II
Abbreviations

JSON JavaScript Object Notation

LoRaWAN Long Range Wide Area Network

LPWAN Low-Power Wide-Area Network

M2M Machine to Machine

MQTT Message Queuing Telemetry Transport

MQTTS Message Queuing Telemetry Transport Secure

MySQL My Structured Query Language

NC Normally Closed

NFC Near-field communication

NO Normally Open

NodeMCU Node Micro Controller

NoSQL No Structured Query Language

OFDM Orthogonal Frequency Division Multiplexing

OQPSK Offset Quadrature phase-shift keying

P2P Peer-to-peer

PaaS Platform as a Service

PLC Programmable Logic Controller

QAM Quadrature Amplitude Modulation

QoS Quality of Service

QPSK Quadrature phase-shift keying

III
Abbreviations

RAM Random Access Memory

RC4 Rivest Cipher 4

RSA Rivest–Shamir–Adleman

SaaS Software as a Service

SD Secure Digital

SDK Software Development Kit

SINR Signal to Interference & Noise Ratio

SMS Short Message Service

SoC System on a Chip

SQL Structured Query Language

SSH Secure Shell Protocol

SSID Service Set Identifier

SSL/TLS Secure Sockets Layer/Transport Layer Security

SSMS SQL Server Management Studio

TCP/IP Transmission Control Protocol/Internet Protocol

TSDB Time-Series Database

UART Universal Asynchronous Receiver-Transmitter

URL Uniform Resource Locator

USB Universal Serial Bus

UTF-8 Unicode Transformation Format

IV
Abbreviations

VB Visual Basic

VCC Voltage Common Collector

VS Visual Studio

WEP Wired Equivalent Privacy

Wi-Fi Wireless Fidelity

WPA Wi-Fi Protected Access

WPAN Wireless Personal Area Network

V
Table of Contents

Title Page

Abbreviations I

Table of Contents VI

List of Figures IX

List of Tables XIII

Abstract XIV

Chapter One: Introduction 1

1.1 Home Automation using Internet-of-Things (IoT) 2

1.2 Project Motivation 2

1.3 Aim and Objectives 2

1.3.1 Aim 2

1.3.2 Objectives 3

1.4 Project Structutre 3

Chapter Two: Background and Literature Review 4

2.1 Introduction 5

2.2 Home Automation Systems 5

2.2.1 The Work Principle of Home Automation Systems 6

2.2.2 Types of Home Automation Systems 7

2.2.3 Home Automation Methodologies 9

2.3 IoT Background 13

2.3.1 IoT Architecture 14

2.3.2 IoT Wireless Communication Technologies 16

VI
2.4 Backend Architecture used in IoT 20

2.4.1 Databases used for IoT 20

2.4.2 Application Programming Interface (API) 22

2.4.3 Local-based and Cloud-Based Controller in IoT 23

2.5 Related Works 26

2.6 Summary 28

Chapter Three: IoT Platform Tools 30

3.1 Introduction 31

3.2 Hardware Tools 32

3.2.1 Temperature and Humidity Sensor 32

3.2.2 NodeMCU 32

3.2.3 Relay Module 33

3.2.4 Raspberry Pi 35

3.3 Software Tools 35

3.3.1 NodeRed 35

3.3.2 MQTT Protocol 37

3.3.3 InfluxDB 41

3.3.4 Grafana 43

3.3.5 Front-end Web-based Dashboard 44

3.4 Summary 47

Chapter Four: System Implementation and Outcomes 48

4.1 Introduction 49

4.2 Establishment of the system (Backend) 49

4.2.1 Preparing the Raspberry Pi 50

VII
4.2.2 Preparing the NodeMCU (Circuit Building) 53

4.2.3 Setting-up the home automation using NodeRed 55

4.2.4 Frontend 71

4.3 System Validation and Outcomes 74

4.3.1 Temperature Monitoring 74

4.3.2 Setting Temperature Thresholds 76

4.3.3 Manual Control from the App 77

4.3.4 Fan Automation 78

4.4 Summary 79

Chapter Five: Conclusions and Future Work 80

5.1 Conclusions 81

5.2 Future Work 81

References 82

A. Appendix 87

A.1 Preparing the Raspberry Pi 87

A.1.1 Installation of OS on raspberry pi use raspberry pi imager 87

A.1.2 Connect raspberry pi to network via wifi 88

A.1.3 The commands to install InfluxDB are as follows 89

A.1.4 The commands to install Mosquitto Broker are as follows 89

A.1.5 The commands to install Node-red Broker are as follows 89

A.2 NodeMCU Specifications 89

A.3 Preparing the NodeMCU 91

A.3.1 Connect NodeMCU network via wifi 91

A.4 The Arduino Code 94

VIII
List of Figures

Figure Number Page

2.1 (Home Automation System ) ________________________________________________ 7

2.2 (Bluetooth-based home automation system) __________________________________ 10

2.3 (WiFi-based home automation system) ______________________________________ 10

2.4 (GSM-based home automation system) ______________________________________ 11

2.5 (IoT-based home automation system) _______________________________________ 12

2.6 (Applications of IoT.) _____________________________________________________ 14

2.7 (Four-layer IoT architecture) ______________________________________________ 14

2.8 (Work Concept of API) ___________________________________________________ 22

2.9 (Deployment and Service Models of Cloud Computing ) ________________________ 24

3.1 (Home Automation Platform System Design.) ________________________________ 31

3.2 (Temperature and Humidity sensors) ___ ________________________________32

3.3 (NodeMCU) ____________________________________________________________ 32

3.4 (Relay Module) __________________________________________________________ 33

3.5 (The high voltage side of the 5 volts relay used during the project.)_______________ 33

3.6 (The first set lower voltage side of the relay used during the project. _____________ 34

3.7 (The second set lower voltage side of the relay used during the project.) __________ 34

3.8 (Raspberry Pi) __________________________________________________________ 35

3.9 (NodeRed Interface.) _____________________________________________________ 36

3.10 (Establishing MQTT connection) __________________________________________ 38

3.11 (Publishing messages in MQTT) __________________________________________ 40

IX
3.12 (Client subscribing and unsubscribing to the topic) ___________________________ 41

3.13 (Influx DB structure.) ___________________________________________________ 42

3.14 (Monitoring System using Grafana)________________________________________ 44

3.15 (SSMS environment.) ____________________________________________________ 45

3.16 (Visual Studio IDE .) ____________________________________________________ 46

3.17 (SQL database and Visual Studio connection) _______________________________ 46

4.1 ( Use the MQTT protocol in the system.) _____________________________________ 51

4.2 (The database "_smarthome" that was designed in the project.) _________________ 52

4.3 (Grafana dashboard to display sensor temperature and humidity.) ______________ 53

4.4 (Setup Wifi and MQTT connection for NodeMCU.) ___________________________ 54

4.5 (NodeMCU Circuit ) _____________________________________________________ 54

4.6 ( Circuit building design)__________________________________________________ 55

4.7 (The First Flow.)_________________________________________________________ 56

4.8 (” MQTT IN” Node Composition.)__________________________________________ 57

4.9 (“Json_Humidity” Node Composition.) ______________________________________ 57

4.10 (“Change Node” Composition.) ___________________________________________ 58

4.11 (“Join Node” Composition.) ______________________________________________ 59

4.12 (“InfluxDB Out” Node Composition.) ______________________________________ 60

4.13 (The Second Flow) ______________________________________________________ 60

4.14 (” HTTP in” Node Composition) __________________________________________ 61

4.15 (“Static Control” Function Code)__________________________________________ 61

4.16 (“Fan Switch” Node Composition.) ________________________________________ 62

4.17 (“MQTT Out” Node Composition) ________________________________________ 63

X
4.18 (“ Function” Node for Setup SMS Message.) ________________________________ 64

4.19 (“IFTTT Out” Node Composition ) ________________________________________ 64

4.20 (The Third Flow.) _______________________________________________________ 65

4.21 (“Function” Node to generate a message ____________________________________ 66

4.22 (File Node Composition.) _________________________________________________ 67

4.23 (The Forth Flow.) _______________________________________________________ 68

4.24 (“File in” Node Composition.) ____________________________________________ 68

4.25 (“Function” Node to turn on the fan.) ______________________________________ 70

4.26 (“Function” Node to turn off the fan.) ______________________________________ 70

4.27 (Login page.) ___________________________________________________________ 71

4.28 (Dashboard page.) ______________________________________________________ 72

4.29 (Grafana panel URL) ____________________________________________________ 72

4.30 (Node-Red flow URL) ___________________________________________________ 73

4.31 (Automation page) ______________________________________________________ 73

4.32 (Sittings page) __________________________________________________________ 74

4.33 (Final shape of the NodeMCU board.) ______________________________________ 75

4.34 (NodeRed Dashboard.) __________________________________________________ 75

4.35 (Temperature Dashboard.) _______________________________________________ 75

4.36 (Humidity Dashboard)___________________________________________________ 76

4.37 (Setting Temperature Thresholds) _________________________________________ 76

4.38 (The temperature set by the user is displayed on the NodeRed interface.) ________ 77

4.39 (Fan Switch is ON.) _____________________________________________________ 77

4.40 (SMS Notification.) _____________________________________________________ 77

XI
4.41 (Fan Switch is OFF) ___________________________________________________ 78

4.42 (SMS Notification) ______________________________________________________ 78

4.43 (The Fun Switch is ON.) _________________________________________________ 78

4.44 (NodeRed Dashboard ) __________________________________________________ 79

4.45 (The Fan Switch is OFF) _________________________________________________ 79

4.46 (SMS Notification.) _____________________________________________________ 79

A.1 (Connect the SD card to Computer.) ________________________________________ 87

A.2 ( Device Manager) _______________________________________________________ 91

A.3 (Enter the ESP8266 library into Additional Board Manager URLs field.) _________ 92

A.4 (Install the ESP8266 library.) _____________________________________________ 93

A.5 (Included the ESP8266 library in the Arduino IDE.) __________________________ 93

XII
List of Tables

Table Number Page

2.1 (Comparison of home automation methodologies.) ____________________________ 13


2.2 (Short-Range Wireless Communication Technologies.) _________________________ 18
2.3 (Long-Range Wireless Communication Technologies.) _________________________ 20
2.4 (Differences between SQL and NoSQL.) _____________________________________ 21
2.5 (Compression between Local-based and Cloud based) _________________________ 25

XIII
Abstract

Abstract

Home automation systems have gained a lot of attention nowadays, as many applications are using
different technologies. However, the current home automation systems lack the use of IoT
technology and have a limited transmission range. Therefore, home automation systems are
shifting towards being based on the Internet of Things, which provides devices with monitoring
capabilities and controls them remotely from anywhere. This project presents a design and
implementation of an IoT-based home automation system, based on sensing the temperature and
humidity of the home and controlling the operation of the cooling device manually through a web
interface or automatically based on a certain temperature. This system is considered low cost,
reduces energy consumption, and meets the needs of the end-user.

XIV
CHAPTER I Introduction

CHAPTER 1
Introduction

1
CHAPTER I Introduction

1.1 Home Automation using Internet-of-Things (IoT)

In the modern world, it has become the trend of people toward the Internet of Things, which has
an important role in improving daily life. Home automation systems have also become one of the
most important technologies after the development of communication technology. The Internet of
Things (IoT) technology is expected to have an extraordinary trend in the future, as it has become
an important technology for connecting billions of smart devices (phones, laptops, sensors, and
motors) to the internet. Home automation is an Internet of Things application that allows users to
control and monitor different home appliances from different devices over the Internet. For
example, lights and door locks can be monitored and controlled via a home automation system [1].
In this project, the intention is to design and implement a home automation platform. The system
to be applied is to monitor the temperature and humidity to control the cooling system
automatically as well as directly control the cooling. This work explains how and when the fan is
controlled by sensing temperature and humidity. It also provides an interface for the end-user to
display the temperature and humidity of the house for periods of time, and a control panel to control
the system.

1.2 Project Motivation

The home automation system is designed using Internet of Things (IoT) to enable users to connect
automatically to home functions, such as monitoring home temperature and turning on/off cooling
systems, lights, and other home appliances to monitor and control the home through a distance. In
addition, home automation systems are an effective way to improve safety, energy management,
and convenience. It also saves energy and reduces its cost.

1.3 Aim and Objectives

1.3.1 Aim
This project aims to design and implement an end-to-end platform for home automation. It is based
on sensing the environmental indoor weather conditions. The sensed data is then forwarded to a
flow-based programming software that enables or disables the cooling device (fan) based on a set

2
CHAPTER I Introduction

of predefined conditions. The sensed data is also stored in a database and displayed on a web-
based dashboard upon the user's request.

1.3.2 Objectives
The objectives of this project are as follows:
● To study the structure of the internet-of-things (IoT) platforms from an end-to-end
perspective.
● To study how IoT components are linked together using multiple media.
● To study the state-of-the-art strategies for designing non-relational (NoSQL) databases for
IoT platforms.
● To Design and implement a simple home automation platform using a combination of
hardware and software tools.
● To implement a web-based dashboard that enables efficient access to the IoT data.

1.4 Project Structure

● Chapter Two (Background and Literature Review):


This chapter introduces the concept of home automation, and the background of the
Internet of Things and the backend architecture used in it.
● Chapter Three (IoT Platform Tools):
It contains a brief description of the system and also presents the system tools, software
and hardware used in the project with a brief description.
● Chapter Four (System Implementation and Outcomes):
This chapter describes the steps for implementing the system and results, and also presents
an evaluation of the system's performance.
● Chapter Five (Conclusion and Future Works):
It includes the conclusion of the project and future work.

3
CHAPTER II Background and Literature Review

CHAPTER 2
Background and Literature
Review

4
CHAPTER II Background and Literature Review

2.1 Introduction

With the increase in energy consumption, the demand to reduce it and find ways to conserve it
increases, Home Automation (HA) is pushing this idea forward to help equip homes in a better
way of living, reduce human effort and achieve greater savings in cost-effective billing [1].
Various methodologies of home automation have been implemented, and the best of them is a
home automation system using Internet of Things (IoT). IoT-based home automation systems
provide the feasibility of operating home automation from anywhere in the world and from any
device using the Internet [1].
This chapter introduces the concept of home automation, how it works and its types. It presents
various methodologies for implementing home automation, including the proposed method; the
IoT- based home automation system. Then provides a background of Internet of things, and an
explanation of database types and which of them is preferred to be used in IoT applications. Then
a comparison between IoT systems based on a local controller or cloud services, and finally some
related work to IoT-based home automation systems.

2.2 Home Automation Systems

Home automation or smart home systems have gained importance nowadays due to the various
applications they provide to users, which cover many aspects of our daily life and help reduce the
cost of living by controlling and managing home appliances. Science fiction has introduced the
concept of home automation for decades, and the American Association of Home Builders
demonstrated it in 1984 [1].
A home automation system is defined as a home with an automated system consisting of sensors,
actuators and controllers to allow users to control and monitor home appliances remotely [1].
In traditional homes switches connected to power lines are used by users to turn on/off household
appliances such as lights, fans, and refrigerators. This is done without obtaining any information
about the energy consumption of these devices, therefore, the user spends a lot of money and effort
to create this type of home control device, also, there are many threats that have begun to appear
on the environment at the present time, such as global warming, climate change and fluctuations
in energy prices. These problems thus contributed to developing home automation systems that

5
CHAPTER II Background and Literature Review

overcome the limitations of traditional homes as they give users the opportunity to interact with
their home appliances and improve the quality of life [1], [2].

There are so many benefits of smart home system which includes:

● Reducing human efforts, as household members can access and control household
appliances from anywhere.
● Helping the elderly and disabled people by accessing and controlling home appliances
remotely, and also in the event of any risky situation, the family will be notified
immediately and can take the appropriate action.
● Saving Electricity, this is done by achieving the principle of using electricity as needed and
according to the requirements of users.
● Alerts, where users can be alerted to events that may occur when leaving, such as gas leaks,
fire and unexpected arrivals to their homes.
● Automation, i.e. it means the application of some action without user interaction, for
example, when the user enters any room the light turns on automatically and after the
person leaves the room light turns off, besides, the user has the option to turn on/off a fan
or air-condition the room based on the room temperature [1], [2].

2.2.1 The Work Principle of Home Automation Systems


In a smart home environment, home appliances with sensors or actuators are directly connected to
the microcontroller as shown in Fig.2.1. A controller such as a NodeMCU, Arduino, or
Programmable Logic Controller (PLC), is a device used to transmit and receive information to and
from sensors and actuators. In the remote environment, computers or smartphones are generally
used as the last user interface that is connected to the main controller in the house for
communication with the home network [1], [3].

6
CHAPTER II Background and Literature Review

Fig.2.1 Home Automation System

Home appliances can be monitored or controlled by giving commands by users, through their smart
devices, these commands indicate the action that the user wants the system to perform. For
example - turning on/off the lights and fan, etc. The user commands are then sent to the
microcontroller to do a certain action, in addition the microcontroller can collect home state data
such as temperature, from sensors to send it to the users' application to be displayed [1].

2.2.2 Types of Home Automation Systems


Home automation applications can be categorized based on communication medium into two
types as follows:

A. Wired System
In these systems, all smart devices are connected to the main control unit via wired
communication by cable, such as optical fibers and bus lines [2].

Wired system has many advantages including [2]:


● Low security risk, because no one can penetrate the wires.
● These systems will not face the problems of wireless systems such as interference,
range and access to communication.
● High speed of transportation.

Disadvantages of automated wired system [1], [2]:


● These systems are expensive in terms of purchasing wires and adapters, and it needs
technical experts to operate this system.

7
CHAPTER II Background and Literature Review

● These systems are considered very inflexible in terms of increasing hardware and
wires.
● It is limited in control range due to limited wire length.

B. Wireless Systems. They are systems that use many applications of new wireless
technology, such as Wi-Fi, Bluetooth and Zigbee for communication between devices in a
smart home environment. It is a more popular method because it is reliable in almost all
sizes and types of homes [1], [2].

Advantages of wireless home automation system [1], [2]:


● The wireless system can be operated with a minimum of wires or without it, so the
cost of this system is very low compared to the wired automation system.
● Easy installation, as installing any device on a wireless system is considered very
flexible, you can expand a number of home controls without tangled wires.
● Wireless technologies provide a large range for users to control their homes,
especially with the advent of the Internet, which enabled them to control at anytime
from anywhere.

Disadvantages of wireless automation system [2]:


● Security risk, because most wireless systems are vulnerable to hacking.
● The speed performance of this wireless system is slow compared to the wired
automation systems.
● Some technologies such as Bluetooth and Wi-Fi force the user to control the devices
from limits and short distances.
● Most such systems need a stable Internet connection to work properly without
delay.

Both wired and wireless automation systems have advantages and disadvantages. But with the
progress of time and the advancement of technology, the use of wires in most communication
systems has decreased, but to take the advantages of the two systems can use it as a more effective
and reliable hybrid system [1].

8
CHAPTER II Background and Literature Review

Home automation systems can be classified into two main categories based on the scope of
control, local and remote control

A. Local Control Systems. Where users can control their home appliances using a Fixed
(wired) cable or wireless communication technology such as (Bluetooth, Zigbee and Wi-
Fi) [1], [3].
B. Remote Control Systems, where users can control their homes remotely from anywhere
through the use of their mobile or personal computers via Internet connection [3].

2.2.3 Home Automation Methodologies


Many different types of communication technologies are used to transmit commands and data from
the user interface to the main controller and back. So we will highlight some methodologies for
creating a home automation system and then show the methodology that has been implemented in
this project.

A. Bluetooth-based Automation System


Bluetooth based home automation systems as shown in Fig.2.2, usually consist of a smart
device (phone/computer) that allows the user to control home appliances and an Arduino
BT microcontroller. Bluetooth is used to send commands from users via their smart devices
to the Arduino BT wirelessly, the Arduino BT receives data, decodes it, and executes the
specified commands. These systems have a high, secure, and low-cost connection rate, so
they can be implemented as a real-time home automation system [4], [5].
But one of the main disadvantages of this system is that it is limited to a range of up to 10
meters, which means that it is not possible to control home appliances if the phone is
outside the range of the bluetooth limiter [4], [5].

9
CHAPTER II Background and Literature Review

Fig.2.2 Bluetooth-based home automation system

B. Wi-Fi-based Home Automation System


Wi-Fi is wireless technology used in home automation systems to connect and transfer data
between smart home devices (phone/computer) and built-in Wi-Fi controller (ESP 8266
12) which is connected to the sensors such as shown in Fig.2.3 [5].

This system is easy to use and cost-effective as it helps to operate home appliances using
smart phones because of its built-in technology. It has the ability to handle large amounts
of data and transmit data over longer distances when compared to other communication
techniques such as Bluetooth, and it can control multiple devices at the same time. But a
limitation of this system is that it consumes energy and has a range of about 40-100 meters,
so it is also considered to be limited in the control range [5].

Fig.2.3 WiFi-based home automation system

10
CHAPTER II Background and Literature Review

C. GSM-based Home Automation System


Global System for Mobile Communications (GSM), is a system developed by the European
Telecommunications Standards Institute (ETSI), GSM is used in home automation systems
to monitor and control home appliances via short message service (SMS) [4].
The hardware structure of this system as shown in Fig.2.4, consists of the following [4]:
● The microcontroller (PIC16F887) that connects to the home appliances to be
controlled or monitored.
● A mobile phone through which users can control their home appliances by
sending/receiving SMS messages.
● GSM modem, which used to read and decode the SMSs received from the mobile
phone number and then send commands to the controller to execute the required
command.
The advantages of a GSM-based automation system are that it provides maximum security,
and due to the wide coverage of the GSM network, network users can access devices from
anywhere in the world where the mobile network is available. The GSM system is suitable
for remote control from anywhere in places where a suitable Internet connection may not
be available [4], [5].
But the limitation of this system is the high cost because it depends on the distance between
the user and the home device, in addition to the lack of an interface that the user can use to
control the devices, and no text message is guaranteed to be delivered to the system at the
same time, so it is not as reliable as a real-time home automation system [4].

Fig.2.4 GSM-based home automation system

11
CHAPTER II Background and Literature Review

D. IoT-based Home Automation System


Although previous home automation methods perform their functions in terms of
monitoring and controlling, they do not have enough functionality and have a set of
limitations because some of them use long-range wireless interfaces, such as GSM which
is expensive and unreliable for real-time systems, or short-range interfaces, such as Zigbee,
Bluetooth and Wi-Fi which are only useful for internal control of household appliances.
The main reason for this is that most of these systems lack the powerful features of IoT
technology [1].
IOT-based home automation means monitoring and controlling home appliances
remotely using the Internet [1]. This system, as shown in Fig.2.5, consists of three sections:
home gateway, home environment, and remote environment [4].
● The home environment contains the main control unit and smart objects that include
sensors or actuators [4].
● The main gateway is that allows communication and exchange of information
between the home environment and the remote environment via the Internet [4].
● The Remote environment where users can control and monitor devices through an
Internet-connected web page or an application in smartphones that support 3G or
4G, Wi-Fi [4].
These systems have the ability to control IoT devices from anywhere in the world, that is,
it has no limited range, which makes it a high-performance data transmission system
compared to other media [5].

Fig.2.5 IoT-based home automation system

12
CHAPTER II Background and Literature Review

Those systems mentioned above mainly use wireless technologies, and each has its own
advantages and disadvantages so that it is used according to the system requirements. Table.2.1
provides a comparison of all systems based on their speed, cost, speed, range and real-time
efficiency.

Table.2.1. Comparison of home automation methodologies. [4], [5].

Technologies Bluetooth Wi-Fi GSM IoT

Cost Low High High High

Speed High Slow Slow Slow

Range 10m 40m wide wide

Real-Time Yes Yes No Yes

2.3 IoT Background

Internet of Things (IoT) has gained the attention of researchers as well as key industries in the past
few decades. Kevin Ashton introduced the term "Internet of Things" in 1999. IoT means
connecting heterogeneous physical devices (things) over the Internet using (sensors, actuators,
controllers, phones, etc.) to collect and exchange data. The collected data is used in many
applications to enhance the results of the decision-making process in various applications [6].
There are countless IoT applications aimed at increasing energy efficiency, managing the life of
“devices” batteries, and benefiting both consumers and service providers. IoT applications are
categorized as customer-based applications (such as smart homes), infrastructure-based
applications (such as smart grids), and industry-based applications (such a smart supply chain) [6].
Some of the Internet of Things applications are shown in Fig.2.6.

13
CHAPTER II Background and Literature Review

Fig.2.6 Applications of IoT.

2.3.1 IoT Architecture


The Internet of Things is a multi-layered architecture that has been proposed to ensure
interoperability of heterogeneous devices. There are many proposed models with different
numbers of layers for IoT architecture, the most common is the four-layer basic model: sensor
layer, network layer, application layer and management layer as shown in Fig.2.7 [6].

Fig.2.7 Four-layer IoT architecture

14
CHAPTER II Background and Literature Review

A. Sensing Layer
It is the layer responsible for connecting physical devices (sensors and actuators),
collecting and controlling data from them and then sending data to the network layer using
an IoT gateway [6].
Sensors are devices in the sensor layer that detect changes in the surrounding environment
and convert them into electrical signals. The choice of any type of sensor depends on the
demand for use, however, the following considerations must be taken when choosing: the
accuracy of the sensors for measuring data, their cost, and battery life, if they are battery
operated [8].
Actuators are also components of a sensor layer that is a physical device designed to
control machine function [8].

B. Network Layer
It is also known as the communication layer, where this layer consists of three functions:
network communication, to allow communication and data routing using different
transmission technologies, such as (Bluetooth, Wi-Fi, LoRa and ZigBee). Storing and
processing constantly flowing data, by which the stored data is used for visualization and
analysis purposes. And cloud services that provide a set of tools for communication,
processing, storage and analysis of IoT data [8].

C. Application Layer
The application layer consists of user interfaces, data visualizations, and IoT services such
as smart home, smart transport and smart healthcare. In other words, this layer allows
comprehensive interactions between the user and IoT devices [6] [8].

D. Management Service Layer


Strictly speaking, this is not a layer because it is linked to all other layers and is responsible
for managing the entire IoT model, error monitoring, and system performance [8].

15
CHAPTER II Background and Literature Review

2.3.2 IoT Wireless Communication Technologies

There are many different types of wireless technologies to connect smart devices in IoT
applications, and these technologies can be categorized into two categories in terms of range, they
are short-range and long-range technologies also known as Low Power Wide Area Network
(LPWAN) [9].

A. Short-Range Technologies
It provides wireless communication within a small coverage space [9]. There are a number
of short-term techniques such as:

● Bluetooth
It is a communication standard by IEEE 802.15.1. It is one of the most popular
wireless technologies, mainly used for mobile devices for interconnection
distributed in a small space. However, classic Bluetooth's high power consumption
makes it impractical for small size IoT devices with limited battery, on the other
hand, Bluetooth Low Energy (BLE) is specially introduced for low energy IoT
devices with better data rate compared to classic Bluetooth [9].

● ZigBee
It is protocol IEEE 802.15.4, was created by ZigBee Alliance which is one of the
widely used transceiver standards; similar to Bluetooth technology, it offers low
throughput, low power operation and low costs, so its benefit is showing in wireless
control networks and sensors in IoT applications [10].

● Wi-Fi
It is the short name for Wireless Fidelity and it generally refers to any type of IEEE
802.11 wireless local area network. Wi-Fi standard is one of the most popular IoT
communication protocols, as it has many advantages including low cost, ease of
use, access to multiple devices, handling large amounts of data, and the ability to
transfer data over longer distances compared to other communication methods such
as Bluetooth and Zigbee [9].

16
CHAPTER II Background and Literature Review

● Z-Wave
Z-wave is a low-power transmission protocol developed by Zensy. It is designed
for IoT applications and especially for home automation, due to its ability to
transmit a small amount of data at a speed up to 100 kb/s over a distance of 30
meters from point to point. Z-Wave is based on two types of hardware (controller
and slave). Slave nodes are low-cost devices that can only respond and execute
commands sent by the control element [10].

● NFC
It is an acronym for Near-field communication, it is a very short range wireless
technology that allows data to be transferred between devices by touching them or
by combining them together [10].
NFC tags is a small chip formatted for use with NFC systems, which contains a
small amount of data. This tag can be read only or can be rewritten or changed later
by the device. NFC technology is widely used in identification applications,
industrial applications, contactless payment systems, and in the communication and
control of IoT devices in various environments [10].

The following table provides a comparison of common IoT short-range communication


technologies.

17
CHAPTER II Background and Literature Review

Table.2.2 Short-Range Wireless Communication Technologies. [9], [10].

Bluetooth Zigbee WiFi Z-wave NFC

Standard IEEE 802.15.1 IEEE IEEE 802.11 b Z-wave ISO/IEC


802.15.4 / a / g / n / ac / 14443
ax

Data rate Classic: 250 kbps 802.11.ac: 40kbs 424 kbps


3Mbps 7Gbps
BLE: 2Mbps

Rang 10m 10-100 m 100m / 30-100m 10cm - 1m


802:11ah: 1km

Topology WPAN WPAN WPAN WPAN P2P


Network.

Frequency 2.4GHz 2.4GHz 2.4GHz /5 868 MHz 125Khz /


Bands GHz 908 MHz 13.56Mhz /
860Mhz

Modulation GFSK BPSK BPSK /QPSK BFSK ASK


/DQPSK /OQPSK /QAM
/DPSK

Security E0 Stream AES-128 WEP/ WPA/ AES-128 RSA


Algorithm AES-128 WPA2/AES AES-128

18
CHAPTER II Background and Literature Review

B. Long-Range (LPWAN) Technologies


LPWAN Technologies provide Wide connections for Low-power and low-cost IoT
devices, among the most common long-range technologies are:

● SigFox
It is a low-energy wireless communication technology that allows transmission of
small amounts of data over a distance up to 50 km. It is designed for communication
between a variety of low-power devices such as sensors and M2M applications
[10].

● Cellular
Cellular technology is well suited for applications that need high data throughput.
And GSM/3G/4G cellular connections can be leveraged in IoT applications that
provide high-speed communications over longer distances [10]. However, it
requires a high cost and more energy consumption. Therefore, it is not suitable for
M2M applications or LAN connections [10].

● LoRa-LoRaWAN
It is a long-term technology that uses Chirp Spread Spectrum (CSS) as a method to
modulate the spread spectrum [10]. It is one of the best performing technologies
that provides connections with longer transmission range, lower power, lower data
rate and provides protected data transmission, where (SINR) Required when the
receiver decodes the data [9].

The following table provides a comparison of common IoT long-range communication


technologies.

19
CHAPTER II Background and Literature Review

Table.2.3 Long-Range Wireless Communication Technologies. [9], [10].

SigFox Cellular LoRa

Standard SigFox GSMA, GSM/ 2G /3G/ 4G. LoRa


Alliance

Data rate 100bps Common Cellular rate 50kbps

Rang 50km Wide 20km

Topology LPWAN LPWAN LPWAN

Frequency Bands 868MHz 902MHz Common Cellular bands ISM bands

Modulation GFSK /DBPSK BPSK /OFDM CSS

Security Partially RC4 AES-128


Algorithm addressed

One communication protocol cannot be the best in all respects, each one has certain specifications
and advantages. The appropriate technology is selected according to the system requirements in
terms of network architecture, range, encryption, security mechanism, and power consumption
[10].

2.4 Backend Architecture used in IoT

An IoT backend provides users with the possibility of developing appropriate IoT ecosystems and
applications, which can be used to interconnect end devices, sensors and applications and to
process relevant data which are then prepared for further visualization.

2.4.1 Databases used for IoT


Large amounts of data are generated every moment by connected objects in IoT. IoT is about the
data those things create and collect. Organizations depend on this data to provide better user
experiences, to make intelligent business decisions and eventually fuel their growth.Yet, none of

20
CHAPTER II Background and Literature Review

this is possible without a reliable database that can handle the massive amount of data generated
by IoT devices [11].
Relational databases such as SQL (Structured Query Language), are known for being flexible and
easy to work with but they aren’t particularly known for their scale, which prompted the creation
of NoSQL databases [11].
Table.2.4 demonstrates the five critical differences between SQL and NoSQL databases.

Table.2.4 Differences between SQL and NoSQL.

SQL NoSQL

SQL databases are relational. NoSQL databases are non-relational.

SQL databases use structured query NoSQL databases have dynamic schemas
language and have a predefined schema. for unstructured data.

SQL databases are vertically scalable NoSQL databases are horizontally


scalable.

SQL databases are table-based. NoSQL databases are document, key-


value, graph, or wide-column stores.

SQL databases are better for multi-row NoSQL is better for unstructured data like
transactions. documents or JSON.

Scalability and the capacity to quickly consume data are the main database requirements for IoT
applications. NoSQL systems are ideal for IoT since they are designed with significant horizontal
scalability, in addition to their effective use of data storage in memory, which would be highly
useful for writing throughput and latency [11], [12].
Now the data itself has some patterns, which is broadly classified as sequential or time-series data
and non-time series data, which is largely non-sequential or arbitrary.
A time-series database (TSDB) is a time series data optimized database. It is specifically designed
to handle time-stamped metrics and occurrences or measurements. InfluxDB is an open-source
NoSQL distributed time series database with no external dependencies. It comes with an HTTP

21
CHAPTER II Background and Literature Review

API built-in, so you won't have to create any server-side code to get started. InfluxDB is built to
be scalable, easy to set up and operate, and to process data quickly. On the other hand, SQL
databases such as MySQL are described as the most used open-source database in the world.
MySQL is a multi-threaded, multi-user, and extremely reliable SQL database server. But "Time-
series data analysis" is the primary reason why developers consider InfluxDB over the competitors
[11], [12].
Generally, the reason for adopting NoSQL time-series databases comes down to scale. While
relational databases have many useful features that most NoSQL databases do not, they are
difficult to scale. And because time-series data piles up very quickly, many developers believe
relational databases are ill-suited for it [12].

2.4.2 Application Programming Interface (API)


API is an acronym for Application Programming Interface, which is a set of procedures and
instructions used to develop software applications. As shown in the Fig.2.8 API acts as a
middleware allowing applications to access and interact with external software components that
have already been implemented by other developers [13].
API can be language independent, so it can be called from multiple programming languages, and
this is a desirable feature that is service-oriented and not tied to a particular process or system [13].

Fig.2.8 Work Concept of API

Methods of APIs Requests


API allows developers to make a call or request information from other applications, this
connection is made using a language called "JSON" as the request payload, and with HTTP as the
connection type which is the same protocol used to access the website [13].

22
CHAPTER II Background and Literature Review

API requests can be categorized into different types according to their functions, as shown in
following:
● Get
Safe method, this request only retrieves information from the resource without modifying
it, which does not change the state of the resource [13].
● Post
It is used to create new sub-resources. POST is not considered secure, as if two identical
post requests are invoked, it will result in two different responses [13].
● Put
It is not a secure method; it is used to update the existing resources on the server. If the
resource does not exist, the API decides to create a new resource [13].
● Delete
This request is used to delete resources. It is inefficient which means if you delete the
resource it will already be removed, requesting the delete API multiple times on the same
resource will not change the result as it has already been removed [13].

Internet of Things and APIS


The concept of the Internet of Things helps us to understand the connection of devices and the
exchange of information between them over the Internet. In fact, many hardware and software are
not directly connected to each other, sometimes the communication is with the help of several
APIs that help in integration with other devices and users. An API is directly related to IoT
software or hardware because it allows safe and authorized exposure of devices and other
developers to access available information, where data can be easily recalled and maintained [13].

2.4.3 Local-based and Cloud-Based Controller in IoT

The wide availability of wireless communications and the low cost of miniature electronic devices
have made it possible to extend the concept of the Internet of Things to include large numbers of
objects embedded with sensors that communicate over the Internet [14].
Data processing and management of IoT devices is done by local devices but in recent times with
the increase of smart objects to deal with them, there is a need for scalable systems, so cloud
services have become the mainstream of IoT applications [14].

23
CHAPTER II Background and Literature Review

A. Cloud-based IoT
Cloud computing is a model that uses shared pools over the Internet to virtualize computing
resources such as servers, networks, storage, and applications [15].
Where cloud architectures provide interoperability, interaction and integration with IoT
devices, especially for organizations that manage a large number of connected devices,
computing also provides scalability and high performance, these are the essential features
today in the world of IoT [14], [15].
There are three common service models for cloud computing services, they are Software
as a Service (SaaS), Platform as a Service (PaaS), and Infrastructure as a Service (IaaS)
[15].
Cloud services are deployed in different ways depending on the distribution of services.
Deployment models fall into three categories: public, private, and hyped clouds [15].

Fig.2.9 shows a brief explanation of cloud computing deployment and service models and
the relationships between them.

Fig.2.9 Deployment and Service Models of Cloud Computing

24
CHAPTER II Background and Literature Review

B. Local-based IoT
The local controller is a physical device used to provide the IoT infrastructure. Software is
installed locally and data is processed at the edge of the network closest to the source.
Moreover, this model provides faster performance potential, which can help application
developers make more real-time responses to data [15], [16].

Local-based vs. Cloud based


There are many basic differences between Local environment and a cloud environment, where the
choice depends on the needs and demands of the system.

Table.2.5 Compression between Local-based and Cloud based, [15], [16].

Cloud-based IoT Local-based IoT

Cost The cost is against the resources you For these systems, they are responsible
use, no maintenance costs. Therefore, for ongoing costs of hardware,
it is considered less expensive software, licenses, and ongoing
compared to local systems. maintenance.

Control Cloud computing acts as a third party All data is fully processed, saved, and
provider, and it does not give controlled locally. This feature is
customers full control . important for organizations that have
privacy concerns.

Scalability Cloud has an automatic scaling feature The ability to scale is limited
that allows it to increase the number of compared to cloud as it places some
resources and devices to keep the restrictions on the developers, as they
system running . are responsible for planning the
growth and expansion of the system.

25
CHAPTER II Background and Literature Review

Cloud-based IoT Local-based IoT

Security Because data is stored on remote The local environment has a certain
servers and hardware/ software can be level of security and privacy for the
controlled and accessed from any presence of data in one place, so it is
device, this means that a third party suitable for organizations that have
can change or delete the stored data highly sensitive information.
without the users' knowledge.

Performance Internet speed is one of the important These architectures do not depend on
issues in cloud computing systems, as Internet connections and data travel far
it does not work efficiently with low from its source like cloud
speed internet connections. environments. This reduces delays and
helps in real-time data processing

There are many pros and cons of IoT based on local or cloud computing environments. Choosing
the appropriate system is based on the requirements of the system, as cloud computing is an
environment that many organizations have at the present time, which is characterized by flexibility,
scalability and low cost. But on the other hand, it has some disadvantages that can be solved in
local systems, such as full control of users, a higher level of security and reliability, and a higher
performance speed in real time.

2.5 Related Works

The developers have introduced many different IoT-based home automation systems that help
residents perform their daily activities better through smartphones from anywhere in the world via
the Internet, at the same time reducing energy consumption.

A design has been presented in reference [17] for a low-cost air quality monitoring system based
on MQTT communication. Where a set of sensors, temperature, humidity, carbon monoxide
sensor, and ozone gas sensor are connected to the main control unit NodeMCU ESP8266, the

26
CHAPTER II Background and Literature Review

NodeMCU collects sensor data and sends it to the MQTT broker. MQTT Broker is an open source
message broker that uses the MQTT protocol for messaging. Node-RED software is used to be a
MQTT subscriber, to receive and process the received data and then send it to a responsive web
application. If the data values exceed the normal range, Node-Red sends alert messages to users
via LINE Notify. However, one of the limitations of this system is the Air Quality Index (AQI),
which its value is not calculated from real-time data, as it needs the value of each type of gas
concentration, so it needs a database to store this data in order to be an integrated air quality control
system [17].

The authors of reference [18] have presented an implementation of an IoT application for home
control and monitoring, focusing on wireless transmission of sensor data from the NodeMCU to
Firebase and then the Android application. The Android app has access to its dedicated Firebase
database to get alerts and control home appliances remotely. This is an IOT system that is easy to
implement and relatively inexpensive for the required sources. However, network response time
can cause a problem while transferring data from NodeMCU to Firebase which may cause delay
in sending a notification to the user [18].

The reference [19] has presented a proposed model for IoT-based home automation that uses voice
to control home appliances. One of the advantages of this is a multimodal system that can be played
either through a web-based application or through the Google Assistant. Initially, Google Assistant
is used to control/monitor the smart home and in case of noise home automation can be connected
in the background to the web-based application. For security, a user access code is used that Google
Assistant will ask for verification, which will prevent unauthorized access to the Smart home, thus,
this home automation is safer, smarter, and more flexible [19].

Authors of [20] have been introduced to a study describing the use of the MQTTS protocol with
an SSL/TLS certificate to establish an encrypted connection and protect the data flow between an
IoT cloud and an embedded IoT system. The demo system consists of an embedded IoT Esp32
Wrower, which connects to a temperature sensor and a UART to USB connection used for Internet
access. MQTT Message Agent configured on PowerEdge server with CentOs 7 operating system
for IoT Cloud. The SSL/TLS v1.2 certificate and port 8883 setup are uploaded to the MQTTS
broker and public key in the Embedded System IoT Esp32 flash memory. IoT clouds use a private

27
CHAPTER II Background and Literature Review

key found in the file system of MQTT Broker. To establish an encrypted protected communication
for messages from both sides [20].

In reference [21], authors aim to develop a home security system by monitoring the status of the
door if it is open or closed and sending notifications to the owner using the IoT and LoRA
technology, where LoRaWAN is a cost-effective technology and long-range transmission with low
data rates. This system uses LoRashield to transmit data from a microcontroller (Arduino Uno) to
LoRagateway. Then LoRagateway connects to the linked server via the IoT platform (Ubidots) to
display the sensor values to the user. But the information (door status) can be better displayed to
users through some of the other applications available [21].

Design and implementation of a smart home system has been introduced in reference [22] that uses
low-cost, open-source resources. It features the low-cost Raspberry Pi 3B microcomputer, which
works as a server for the MQTT mosquitto broker, to send messages from the ESP8266 NodeMCU
to Node-red. The Node-RED flow receives, processes and displays data on its dashboard for users
[22].

Accordingly, the proposed project presents the design and implementation of an IoT-based home
automation system that enables users to monitor the temperature of their homes and control the
fan manually or based on temperature, using a Raspberry Pi as an MQTT server that receives
sensor data from the NodeMCU via Wi-Fi, and sends it to Node-red to process the data, as well as
store it in the Influx DB and then display it on Grafana, so that it can share it on the final web-
based interface, which users can access online after verifying their identity.

2.6 Summary

This chapter introduced the concept of home automation in general, which is a system that helps
residents to perform their household activities using electrical energy with less human effort. As
many systems appeared, they depend on different communication technologies, each with some
advantages and disadvantages, but most of them were not enough because their control range is
limited.

28
CHAPTER II Background and Literature Review

The deployment of the Internet of Things allowed home automation systems to control and monitor
home conditions in real-time regardless of the user's location. A background on the concept of IoT
and wireless technologies used to communicate between devices was discussed, and a comparison
between the types of databases showed that NoSQL unstructured databases are faster and better at
performing for IoT huge data. In IoT, there are two systems, depending on the server that manages
and processes the data, whether it's local or using cloud services which is the most used direction.
Finally, some related works to IoT applications, as are distinguished from each other by the
different tools and techniques they use.

29
CHAPTER III IoT Platform Tools

CHAPTER 3
IoT Platform Tools

30
CHAPTER III IoT Platform Tools

3.1 Introduction

Internet-based home automation is an Internet of Things application that allows users to control
and monitor various home appliances from different devices on the internet [23]. In this project, a
home automation system is designed, which saves comfort, energy and improves the quality of
life. Fig.3.1 shows complete work structure and various integration hardware and software
together, from the user's smartphones to changing the state electronic devices for the home. In
hardware design, the Raspberry Pi is used as the main body of the system (Server /Mosquitto
medium) where NodeMCU and Raspberry Pi communicate over Wi-Fi using the MQTT protocol
Which sends information to and from the Raspberry Pi for processing, the DHT11 sensor is a
temperature and humidity sensor that is connected with a fan to the NodeMCU to form a complete
system. In software module design Node-red is used to perform program tasks on data sent from
NodeMCU, InfluxDB is used to store serial data for temperature and humidity, Grafana software
is also used to create a dashboard containing temperature and humidity values stored in InfluxDB
and share them via the API in End user interface. The final user interface consisting of a website
built with Visual Studio and a SQL server database, is designed to save users' data. In this chapter,
both hardware and software tools are introduced and how they are used in the system.

Fig.3.1 Home Automation Platform System Design.

31
CHAPTER III IoT Platform Tools

3.2 Hardware Tools

Hardware tools are part of the system components. This section presents the hardware tools and
their functions used in the project.

3.2.1 Temperature and Humidity Sensor


The temperature and humidity sensor is a low cost digital temperature and humidity sensor used
to provide the temperature and humidity of the air at any given point or location. The DHT11
sensor has three pins: GND is short for ground and Data and
VCC is the power supply voltage. The voltage range of the
VCC pin is 3.5V to 5.5V. The DHT11 digital temperature
and humidity sensor is used in this project for its high
quality, fast response, high anti-interference ability, lowest
Fig.3.2 Temperature and Humidity Sensor power consumption, small size and transmission distance
of 20m [24]. The temperature and humidity sensor is
shown in Fig.3.2.

3.2.2 NodeMCU
NodeMCU (Node Micro Controller) is an open source hardware and software development
environment built on a SoC (System on a Chip) called ESP8266 as shown in Fig.3.3. The
NodeMCU consists of a circuit board that is programmable
in several ways [1]. In this project NodeMCU was
programmed using Arduino, which is the easiest and most
popular method [25]. NodeMCU is mainly used to collect
data obtained by sensors and upload the data to an IoT
server. This microcontroller receives commands given by
users via smartphones or laptops to perform a specific task
Fig.3.3 NodeMCU. and can also connect objects and allow data transmission
using Wi-Fi technology [26].

32
CHAPTER III IoT Platform Tools

● The NodeMCU board consists of an ESP8266 chip. It is a low-cost WiFi chip developed
by Espressif Systems that consists of a microcontroller and a full TCP/IP suite.
● The ESP8266 contains the basic elements of a computer: CPU, RAM, networking (WiFi)
and even a modern operating system and SDK.
● The ESP8266 is a very popular chip for developing IoT devices and this makes it an
excellent choice for IoT projects of all kinds [25].

3.2.3 Relay Module


A relay is an electrically operated switch and like any other switch, it can be turned on or off,
allowing current to pass through or not. It can be
controlled at low voltages, such as 3.3V provided by
ESP8266 GPIOs and allows us to control higher
voltages such as 12V, 24V or mains voltage. There are
different relay modules with different numbers of
channels. One channel, two channels, four channels,
Fig.3.4 Relay Module. eight and even sixteen channels can be found. Where
the number of channels determines the number of outputs that can be controlled. Fig.3.4 shows a
two-channel relay module where the left side of the relay module consists of two connectors that
connect to the high voltage, and the pins on the right side (low voltage) connect to the ESP8266
GPIOs [27].
The high voltage side has connectors that have three sockets as in the Fig.3.8:

Fig.3.5 The high voltage side of the 5 volts relay used during the project.

33
CHAPTER III IoT Platform Tools

● Common (COM): The position of the current you want to control (mains voltage).
● NC (Normally Closed): NC is COM pins connected, which means current flows
unless a signal is sent from the ESP8266 to the relay module to open the circuit and
stop the flow of current.
● NO (Normally Open): There is no communication between the NO and COM pins,
so the circuit breaks unless you send a signal from the ESP8266 to close the circuit
[27].
The low voltage side has two sets of pins:
● The first set consists of VCC and GND to power the unit and input 1 (IN1) and
input 2 (IN2) to control the lower and upper relays, respectively as shown in
Fig.3.6.

Fig.3.6 The first set lower voltage side of the relay used during the project.
.
● The second set consists of GND, VCC and JD-VCC pins as shown in Fig.3.7 [27].

Fig.3.7 The second set lower voltage side of the relay used during the project.

34
CHAPTER III IoT Platform Tools

3.2.4 Raspberry Pi
The Raspberry Pi is a simple and affordable credit card-sized computer. This small device is able
to perform all the tasks that a desktop computer does, such as surfing the Internet, playing games,
and more. In addition, it has the ability to interact with the outside world.
The Raspberry Pi has Micro SD card ports, a Micro USB power supply, and a camera cable port
as shown in Fig.3.8. Raspberry PI is the core of
the home automation system for smart home
monitoring, tracking and analysis. The values
collected by the Raspberry Pi can be read via a
website that reads the values from the cloud or on
an Android mobile device. Raspberry Pi collects
all information from sensors connected directly
Fig.3.8 Raspberry Pi to the device to be processed and stored [28]. In
addition to enable the user to continue reading the various parameters in the system, such as:
humidity, temperature, etc. [29]. Raspberry Pi has been used in digital fabrication projects such as
music instruments, etc. [28].

3.3 Software Tools

To implement this system, several software components were used. In this section, the
programming tools used and their functionality in the project will be presented.

3.3.1 NodeRed
Node-RED is an open source, flow-based programming tool developed by IBM since 2013. It is a
JavaScript-based tool, built on the Node.js platform, which provides a browser-based visual flow
editor [30]. They are used to create IoT applications due to their ability to connect devices, APIs,
and online services together in new ways [31]. It can be run on the cloud or run locally with a
Raspberry Pi [32]. Node-Red is an easy-to-use model due to the user's ability to discover the
problem by looking at the flow without having to understand lines of code [31]. The application
can be created in Node-RED in two ways: dragging a node from the Nodes panel into the
workspace and linking them together, or importing JavaScript code. It is also possible to install

35
CHAPTER III IoT Platform Tools

multiple additional nodes in the nodes board [33]. It allows describing the behavior of the
application in the form of a series of "nodes" that make up a network, where each node has a
specific purpose that it performs after giving it some data, for example, data processing, controlling
objects, or sending alerts, flows data between nodes based on a sequence [31] [34]. Streams are
stored using JSON [33].

The Node-RED user interface consists of three main parts:


● Node Panel.
● Flow Panel.
● Info and Debug Panel.

In Fig.3.9 the interface of the Node-RED editor is shown. The flow panel is in the middle of the
user interface where nodes are dragged and connected to each other to create the flow, and on the
left side is the nodes panel which contains a group of combined nodes that perform different tasks.
On the right side is the Info and Debug panel which contains two tabs: Info and Debug. If you
click Debug, debugging information, errors, and warnings are displayed, and if you click
Information, the results of the selected nodes are displayed.

Fig.3.9 NodeRed Interface.

36
CHAPTER III IoT Platform Tools

3.3.2 MQTT Protocol

MQTT is an acronym for Message Queue Telemetry Transport, it is a lightweight


publish/subscribe based messaging protocol. It is designed to connect clients to the server (broker)
over the low bandwidth, and subscribe or publish data between them. MQTT was invented in 1999,
by Andy Stanford-Clark (IBM) and Arlen Nipper (Arcom, now Cirrus Link), and has recently been
introduced as standard communications protocol by OASIS [35]. The MQTT protocol is based on
TCP/IP, it uses IANA registered port number 8883 for SSL/TLS connections, and 1883 port
number for Non-TLS connections.MQTT has many advantages that make it an ideal
communication protocol for M2M and IoT systems [36].

Some features of the MQTT protocol:

● Its ability to connect millions of devices online Lightweight.


● Open source.
● Low bandwidth.
● High quality data delivery (QOS).
● Simple and easy deployment.

Any MQTT connection has two kinds of agents:

● An MQTT client.
● An MQTT server (MQTT broker).

An MQTT Client: is a software or device such as a sensor, mobile or microcontroller etc.


It uses the MQTT protocol to open a connection to the MQTT broker and exchange
messages. The client can be either a publisher or a subscriber [36].

● The publisher creates a message containing payload data, quality of service, a set
of properties, and a topic name, then it publishes the message to the broker [36].
● The subscriber requests application messages from the server that is interested in
receiving based on topic name [36].

37
CHAPTER III IoT Platform Tools

An MQTT Server (MQTT Broker): is a software or device based on the MQTT protocol
to make, manage and control communications between clients (publishers and subscribers),
which is responsible for accepting communications from clients, receiving all messages
published by publishers, filtering incoming messages and identifying clients interested in
the message based on the message subject (topic), then publish the message to all
subscribed clients and close the network connection [35], [36]. There are many MQTT
brokers such as Mosca/Aedes, Mosquitoes and HiveMQ.

A. Establishing MQTT Connection

An MQTT connection is established between the MQTT client and the MQTT broker directly, and
there is no direct connection between the client and any other client.

The connection between the client and the broker MQTT consists of several steps as in the
Fig.3.10, which are as follows:

Fig.3.10 Establishing MQTT connection.

38
CHAPTER III IoT Platform Tools

● When the client wants to connect to the MQTT server, the client initiates the connection
by sending the CONNECT packet to the server.
● In response, the moderator sends a CONNACK packet and a status code indicating the
status of the connection.
● After a certain time has elapsed, the connection between the client may be terminated and
the server.
● To avoid this, the client passes a PINGREQ packet to the broker to indicate that it is alive.
● The MQTT server responds to the client by sending a PINGRESP packet and keeps the
connection alive.
● The connection is kept alive until the client sends a DISCONNECT packet to the broker to
disconnect [35], [37].

MQTT is designed to simplify execution on the client by concentrating all the complexities in the
medium. Publisher and Subscriber are isolated from each other which means they do not need to
know that both exist. Before sending application messages, control packets are exchanged based
on the quality of service associated with them and the application of this varies at the publisher
and subscriber.

B. Publishing the Application Messages

If the customer wishes to act as a publisher, it sends a publishing packet to the medium with all
the details regarding the level of service quality, the topic, message payload, etc. MQTT supports
three levels of Quality of Service (QoS) [35] to the client as in the Fig.3.11:

● If the customer transmits the message with QoS 0, no acknowledgment is received from
the moderator.
● If application messages are sent with QoS 1, the server acknowledges the package
published with PUBACK including the package ID.
● However, in QoS 2, four packets are exchanged. The server acknowledges the receipt of
PUBLISH packet with the PUBREC packet. MQTT client then sends a packet to release
publish with a PUBREL packet. The server then sends the fourth packet PUBCOMP,
indicating the completion of publishing the application message on the given topic.

39
CHAPTER III IoT Platform Tools

Fig.3.11 Publishing messages in MQTT.

C. Subscribing to a Topic

If the MQTT client want to subscribe to the application messages published on topic, it sends the
SUBSCRIBE packet along with the topic name. The server acknowledges the subscription with
SUBACK packet along with a return code denoting the status of request. Once the subscription is
successful, the application messages on the specified topic are forwarded to the client with the
maximum QoS. To unsubscribe a topic, the client sends an UNSUBSCRIBE packet to the server
which acknowledges it with the UNSUBACK packet [35], [37] as shown in Fig.3.12.

40
CHAPTER III IoT Platform Tools

Fig.3.12 Client subscribing and unsubscribing to the topic.

3.3.3 InfluxDB
InfluxDB is an open source schema less time series database (TSDB) platform, created by Influx
Data and developed with Go Programming. It is designed to handle real-time data that changes
over time and to provide fast and high-availability storage space for data in many fields such as
monitoring environments, real-time analytics and IoT sensor data. That is, it is much faster than
traditional databases. A custom SQL-like query language called InfluxQL is used to query data
structures, which was built specifically for time series data. The default port for Influx DB is 8086,
and it can run locally on a single node or on the cloud [38], [39].

Influx database structure:

The Influx database has some key concepts in its structure that must be defined, among
which are:
Measurement: a measurement is similar to the concept of a table in relational databases.
Measurement is inside which a data is stored and a database can have one or multiple
measurements [39].

41
CHAPTER III IoT Platform Tools

Each record stored inside of a measurement is known as a point. Point is similar to row in
relational database. Each point is uniquely identified by its series and timestamp [39]. A
point is made up of the following:

● Time: a time is a column called timestamp. All data in InfluxDB has that column,
and the timestamp that represents the time in which the data was recorded.
● Field: a field (another term for attributes) is similar to a not indexed column in a
relational database, each field consists of field key and field value. Field keys are
strings; it tells us that the field values. Field values are actual data, values can be
strings, floats, integers, or Booleans. Each point must contain one or more fields.
● Tags: A tag is similar to an indexed column in a relational database, each tag
consists of tag key and tag value. Both tag keys and tag values are stored as strings.
Each point can contain zero or more tags [39].
The key difference between Tag and Field is that tags are indexed and fields are not
indexed. This means that queries on tags are faster and that tags are ideal for storing
commonly-queried metadata [39]. The structure of an InfluxDB will be illustrated in
Fig.3.13.

Fig.3.13 Influx DB structure.

42
CHAPTER III IoT Platform Tools

3.3.4 Grafana
Grafana is an open source software tool, invented by Torkel Ödegaard and programmed in the Go
programming language and Node.js, which provides a comprehensive web interface that
transforms time series database data into graphs and visualizations that are easy to analyze and
understand. Grafana connects to every potential data source, usually referred to as databases like
InfluxDB, MySQL and Prometheus, etc. [38], [40]. To produce dashboards to help query, monitor
and display data in real time, so it's one of the best options when it comes to broadcast data
visualization such as weather, network devices, sensors, etc. [38].

Grafana Tool Features:

● Create dashboards using visualization tools such as heat maps, graphs, and charts
in any way the user wants.
● Dynamic and reusable dashboards can be created using template variables (data
sources).
● Alert, with Grafana the most important metrics will be visually alerted, and
notifications will be sent to users.
● Grafana is a server-side application, so it consumes less memory and CPU density,
simply because a lot of Grafana's work is done in the browser.
● Prevent unauthorized access to users in Grafana, by setting a custom username and
password.
● Grafana can be run locally or hosted on any cloud platform of your choice (Grafana
Cloud) [38].

Grafana Monitoring System:

Grafana is designed for the purpose of data visualization and presentation in the form of
dashboards. To complete this process, it will go through several stages, data collection, data
storage, data monitoring, as shown in Fig.3.14.

43
CHAPTER III IoT Platform Tools

Fig.3.14 Monitoring System using Grafana.

● Data Collection: It is the process of collecting information from an application, then


sending that data to data stores.
● Data storage: the proposed use is a database (InfluxDB), where time series data are stored
and analyzed.
● Data Monitoring: It is the last part, where Grafana is a tool for querying, presenting and
monitoring data in graphical forms based on the selected data source. The default HTTP
port that Grafana is listening on is 3000.

3.3.5 Front-end Web-based Dashboard


A web-based graphical user interface (website) has been developed that enables users to enter and
navigate within the website, to monitor the internal environment and control smart home devices
via their smart devices (phone/computer). To create this interface, two types of software are
needed: SQL Server Management Studio and Visual Studio IDE.

A. Sql Server Management Studio


SQL Server Management Studio (SSMS) is an integrated environment that provides
graphical tools to configure, monitor and manage any SQL infrastructure, wherever it is
located - on a local computer or in the cloud. The first released version of Microsoft was
SQL Server 2005 and the latest version is 18.11 which was released in 2022 [41].
SSMS software allows users to perform a variety of tasks, such as designing databases,
backing up data and editing queries within a single interface. The database that can be
created in this environment is an SQL Server database, which is a structured, relational

44
CHAPTER III IoT Platform Tools

database that organizes data using a set of tables. Tables are organized in such a way that
they have columns (fields) that contain a set of data values for a given data type [42].
Fig.3.15, shows the SSMS environment with an example of an SQL database that contains
tables with columns and rows representing data.

Fig.3.15 SSMS environment.

B. Microsoft Visual Studio


Visual Studio (VS) is an integrated development environment (IDE) that was introduced
to develop a graphical user interface (GUI), web applications, mobile applications and web
services, etc., as it is a platform that you can use for editing, debugging, and building code.
VS was developed by Microsoft, the first version was 5.0 released in 1997, the latest
version is 17.1.0 which was released in 2022. It provides support for many different
programming languages for interface design and coding, such as C#, C++, VB (Visual
Basic), JavaScript, CSS, HTML and many other languages [43], [44].
Fig.3.16 shows the Visual Studio environment with an open project showing the main
windows.

45
CHAPTER III IoT Platform Tools

Fig.3.16 Visual Studio IDE .

Microsoft created SQL server database and Visual Studio, for allowing
an effective collaboration between them [42].
Where Visual Studio is used to create web applications to access and
manage the database, this means that the Visual application provides the
interface between the user and the database. This interface allows the
user to tell the database what they need and allows the database to
respond to the request and display the requested information in some
way on the interface [44].
A Visual application cannot interact directly with a database as shown
in Fig.3.17. There is a set of middleware components that allow
communication between an application and a database known as
ADO.NET Data Objects [44].

46
CHAPTER III IoT Platform Tools

3.4 Summary

With different home automation systems, the tools required to create it differ, this chapter intended
to contribute to the greater understanding of the tools used for the proposed home automation
system, which consists of two aspects, hardware, and software. These tools work with each other,
from home electronics to the end-user interface, to create an integrated system that provides
simplicity, flexibility, and convenience to improve the quality of life.

47
CHAPTER IV System Implementation and Outcomes

CHAPTER 4
System Implementation and
Outcomes

48
CHAPTER IV System Implementation and Outcomes

4.1 Introduction

Internet of Things (IOT) home automation system means monitoring and controlling home
appliances remotely using the concept of IOT [27]. In the previous chapter of the book, some of
the different methods used to set up a home automation system were highlighted. This chapter
describes the steps for implementing the system and the results obtained.

4.2 Establishment of the system (Backend)

The proposal was implemented for smart home using NodeMCU to control home appliances and
relies on Wi-Fi as a means to connect to the server as well as use MQTT which is a transfer
protocol. Also use some other hardware like the DHT11 temperature and humidity sensor,
Raspberry Pi Zero (server/broker), and a simple fan. Some software such as NodeRed has also
been used to perform programming tasks in the system, Arduino IDE which is used to program
the microcontroller, Grafana to create dashboard for system data, InfluxDB to save sensor data
and Visual Studio has also been used to design web pages. The following steps are the successive
steps to implement the system:

● Set up basic Raspberry Pi settings and connect it to the network via Wi-Fi.
● Connect the temperature and humidity sensor to NodeMCU.
● Connect a simple fan to the NodeMCU.
● Connect the NodeMCU to the Raspberry Pi via WiFi.
● Install NodeRed on the Raspberry Pi.
● Set-up the home automation using NodeRed.
● Install MQTT and establish the connection between the end-device and the gateway.
● Design the database using InfluxDB to save the end-device data (back-end).
● Develop the front-end to display the end-device data (front-end).

In the following sections, shown in detail how to implement each of these points.

49
CHAPTER IV System Implementation and Outcomes

4.2.1 Preparing the Raspberry Pi


Raspberry Pi is used to control the flow between the mobile device and sensors (connected
drives) [45]. Before starting to work on the Raspberry Pi, it is necessary to perform the
following steps:

1. Installation of the Operating System on a Raspberry Pi: As a first step, the


operating system must be installed on the Raspberry Pi. Raspbian is the operating
system used on this platform. It is a versatile operating system, created by the Pi
foundation. It is based on the integrated ARM infrastructure processing unit (CPU)
[33].

2. Connect Raspberry Pi to The Network via WiFi: The Raspberry Pi must be


provided with an SSID and password to be able to connect via WiFi to the LAN
network. There are several ways to connect a Raspberry Pi to a network. One of
them is the wpa_supplicant file method.

3. Installation of Mosquitto Broker on the Raspberry Pi: MQTT broker is installed


on the Raspberry Pi to set it up as an MQTT server/broker. In this system,
“Mosquito” is used as a medium for messages. Mosquitto is a lightweight and open
source MQTT broker suitable for use on all devices from low-end devices power
panels for full MQTT servers to posting and subscribing to messages. Publishing
and subscribing the pattern occurs as discussed in Chapter 3.

Fig.4.1 shows how the MQTT protocol is used in this system. MQTT is used as a
transfer protocol between NodeMCU and Raspberry Pi; and between NodeRed and
Raspberry Pi. NodeMCU and NodeRed are MQTT clients and Raspberry Pi is the
Mosquito broker. The temperature and humidity sensor publishes the
measurements to the MQTT broker, and the Node red acts as a subscriber to receive
these measurements from the MQTT broker and also acts as a publisher if a specific
request is posted to be executed via the NodeMCU on a simple fan.

50
CHAPTER IV System Implementation and Outcomes

Fig.4.1 Use the MQTT protocol in the system.

4. Installation of NodeRed on the Raspberry Pi: Node-Red is installed on the


Raspberry Pi and is used due to its speed in IoT programming [32]. It was used in
this system to receive, process and store the data of "temperature and humidity
measurements'' from the NodeMCU microcontroller in the "InfluxDB'' database, as
well as to execute and execute any user control command on the fan. In this system,
Node-Red runs locally on the Raspberry Pi, and can be accessed via the browser by
entering the IP address of the Raspberry Pi followed by the port number 1880. The
prepared flow will be detailed in Section (4.1.3).

5. Installation of InfluxDB on the Raspberry Pi: InfluxDB is installed on the


Raspberry Pi to store temperature and humidity sensor data in the system due to its
speed in storing time series data. InfluxDB is accessed via a Raspberry Pi by typing
"Influx" on the command line. In this project, a database named "_smarthome" was
created that contains two columns, one for temperature and one for humidity, in
addition to the time column as shown in the Fig.4.2. The purpose of this database
is to hold home temperature and humidity data for later use and display on the user
interface.

51
CHAPTER IV System Implementation and Outcomes

Fig.4.2 The database "_smarthome" that was designed in the project.

6. Installation of Grafana on the Raspberry Pi: Grafana is installed on a Raspberry


Pi for use in visualizing system data (temperature and humidity measurements) in
sequential form for certain time periods depending on its ability to connect to
different data as well as our ability to share this dashboard on the end user interface.
The Grafana is accessed via the browser by entering the IP address of the Raspberry
Pi followed by the port number “3000” as in Fig.4.3. A dashboard called "Sensor
Data" has been created. Then inside the "Sensor Data" dashboard the panels were
created and linked to the "_smathome database" to represent the temperature and
humidity values as in the Fig.4.3.

52
CHAPTER IV System Implementation and Outcomes

Fig.4.3 Grafana dashboard to display sensor temperature and humidity.

4.2.2 Preparing the NodeMCU (Circuit Building)


The main part of the IoT based home automation system is the microcontroller. In this project, a
NodeMCU tool was used to connect the temperature and humidity sensor, fan and relay module
to collect data and send it via Wi-Fi to the NodeRed software on the server. A program was written
in NodeMCU to take the extension temperature from the sensor and then propagate the temperature
value to the MQTT factor. The ESP8266 is also programmed to connect to WiFi in addition to
being programmed to work as an MQTT client. The Arduino IDE is the software used to program
the NodeMCU ESP8266. The "ESP8266" library is included in the Arduino IDE to enable us to
connect to the server via WiFi, the "PubSubClient" library required to allow the ESP8266 to
publish/subscribe to messages from the MQTT broker is also included. The Arduino code contains
the SSID and password of the module you are connecting to the router and also includes the IP
address of the MQTT server as shown in Fig.4.4. Below it will be shown how to connect the
temperature and humidity sensor to the microcontroller and connect the fan to the NodeMCU via
a relay module.

53
CHAPTER IV System Implementation and Outcomes

Fig.4.4 Setup WiFi and MQTT connection for NodeMCU.

1. Connecting the Temperature and Humidity Sensor to NodeMCU:


The Node-MCU was connected to the circuit board and then the temperature and humidity
sensor was connected to the microcontroller by connecting the VCC pin of the sensor to
3.3V of the Node-MCU and the data pin to GPIO pin 13 (D7) and connecting the GND
pin to the Node-MCU GND, as is It is shown in the Fig.4.5.

Fig.4.5 NodeMCU Circuit.

54
CHAPTER IV System Implementation and Outcomes

2. Connecting a Simple Fan to Relay Module to the NodeMCU:


The two-channel relay module is connected to the ESP8266 as shown in Fig.4.6. The relay's
GND pin is connected to the NodeMCU's GND pin, pin IN1 to GPIO pin 5 (D1) and pin
VCC to pin VIN. The fan is also connected to the relay via (NC), then the fan and
NodeMCU are connected to the mains.

Fig.4.6 Circuit building design

4.2.3 Setting-up the home automation using NodeRed


There are four types of processing flows that are designed and they are as follows:

1. The first flow consists of five types of nodes:

The first flow is designed to receive data from an MQTT broker, enter that data into an
InfluxDB database, and simultaneously send the data to be displayed on the Node-RED
dashboard as a measurement chart file. Flow displays in Fig.4.7.

55
CHAPTER IV System Implementation and Outcomes

Fig.4.7 The First Flow.

● The node "MQTT in" where there are two of them in this flow as in the Fig.4.7, one
of them is called "temperature", which subscribes to the topic name
"room/temperature" for MQTT Broker on "localhost" via port "1883" as shown in
the Fig.4.8. The second is called "humidity" which subscribes to the topic name
"room/humidity" for the MQTT broker is also "localhost" and the port number is
1883. Whereas, the MQTT broker is the Mosquitto broker created in the previous
section, where the Nodered and MQTT broker are on the same Raspberry Pi.

56
CHAPTER IV System Implementation and Outcomes

Fig.4.8 “MQTT IN” Node Composition.

● Two “Json” nodes called "json_Temperature" and "json_Humidity" which are each
associated with a "MQTT in" node to convert data between a JSON string and Obj
where the imported values from "MQTT in" are in the form of a JSON string.

Fig.4.9 “Json_Humidity” Node Composition.

57
CHAPTER IV System Implementation and Outcomes

● The "Change" node, where there are also two of them, is to convert the topic name
"Room/Temperature" and "Room/Humidity" to "Temperature" and "Humidity" to
be used in the next node. The configuration of the node is shown in Fig.4.10.

Fig.4.10 “Change Node” Composition.

● The 'Join' node generates a message in the form of a 'key/value object' where the
key is the name of the subject coming to the node, the two are 'temperature' and
'humidity' and the values are the values of temperature and humidity as shown in
the node composition in the Fig.4.11.

58
CHAPTER IV System Implementation and Outcomes

Fig.4.11. “Join Node” Composition.

● The "Influxdb out" node connects to the InfluxDB database server at IP address
127.0.0.1 on port 8086 and inserts data from the "Join" node to the "Station" table
in the database "_smarthome" where the key name in the message coming from the
“Join” node is the name of the column in the database. The composition of this
node is shown in Fig.4.12.

59
CHAPTER IV System Implementation and Outcomes

Fig.4.12 “InfluxDB Out” Node Composition.

2. The second flow consists of six nodes:

The second flow is designed for manual control of the system where a specific command
is received from the user to start or disable the fan and this control is sent through the
MQTT broker to the NodeMCU. The stream also sends a notification to the user to report
the fan's status.flow displays in Fig.4.13.

Fig.4.13 The Second Flow.

● The "HTTP in" node uses the Post method to receive data via the URL "SmartHomestatic"
in the form of a message from the user where a command is received to turn the fan on or
off. The composition of this node is shown in Fig.4.14.

60
CHAPTER IV System Implementation and Outcomes

Fig.4.14” HTTP in” Node Composition.

● The "Change" node was used via the "Set" property to change the outgoing message and
make it contain a command line from the user among the lines of messages received from
the HTTP in the node.

● The "Function" node called "Static Control" was used to control whether the fan was turned
on or off according to the command sent by the user. The composition of this node is shown
in Fig.4.15.

Fig.4.15 “Static Control” Function Code.

61
CHAPTER IV System Implementation and Outcomes

● The "ui_switch" node named "Fan Switch" is a node that receives message data by turning
the fan on or off from the "Function" node and then executes the received state by changing
the color and icon of the switch by default on the Node-RED dashboard page and also
contains the topic name "room/fan" as shown in the Fig.4.16.

Fig.4.16 “Fan Switch” Node Composition.

● The "MQTT Out" node publishes the topic name "Room/Fan" with the message that holds
the control status of the MQTT broker on localhost via port 1883 and then the MQTT

62
CHAPTER IV System Implementation and Outcomes

broker sends it to the subscriber NodeMCU. The composition of this node is shown in
Fig.4.17.

Fig.4.17 “MQTT Out” Node Composition.

● The "HTTP Response" node is used to send responses to the user's page as a result of
requests from the “HTTP in” node.

● The “Function” node is used to setup the message which is sent to the user as a notification
which contains the fan on/off status as shown in Fig.4.18.

63
CHAPTER IV System Implementation and Outcomes

Fig.4.18 “Function” Node for Setup SMS Message.

● The “IFTTT Out” node is used to post messages from the functional node to the IFTTT
channel, IFTTT was used to provide the service of sending a notification to a specific user
via SMS and informing him of the fan status (on/off). Fig.4.19 shows the composition of
the nodes. It contains the key and event provided by the IFTTT site to bind the nodes.

Fig.4.19 “IFTTT Out” Node Composition.

64
CHAPTER IV System Implementation and Outcomes

3. The third flow consists of seven types of nodes:

The third flow is designed for automatic control where the measurement of the maximum
and minimum temperature specified by the user is received and based on these values, the
operation of the fan will be controlled automatically, and these values are kept in a CSV
file for use in the next flow. The flow is shown in Fig.4.20.

Fig.4.20 The Third Flow.

● The "HTTP IN" node that uses the post method to receive data via the URL
"Smarthomeautoma" where a message is received from the user containing the minimum
and maximum temperatures, and based on these values the fan turns on and off
automatically.

● The "Change" node, of which there are also two in this stream, is called "Set
Temp_Max_Value" and "Set Temp_Min_Value" to set the maximum and minimum
temperature value between lines of messages from “MQTT in” node.

● "Join" nodes named "join user temperatures into an array" used to receive the value of the
upper and lower temperature to compose a single message in the form of "Array".

65
CHAPTER IV System Implementation and Outcomes

● The “Function” node is used to generate a message in the form of a JSON string where a
name is generated representing each value in the array created from the previous node. The
composition of the node is shown in Fig.4.21.

Fig.4.21 “Function” Node to generate a message


in the form of a JSON string.

● The "File" node named "Temperature value file by the user" creates a file named
"Temp_degree" on Raspberry Pi with the extension "/home/pi/logs/Temp_degree.csv" to
be used in saving the maximum and minimum temperature values specified by the user due
to the need to implement an automatic control where the entire file is overwritten rather
than appended. The composition of the node is shown in Fig.4.22.

66
CHAPTER IV System Implementation and Outcomes

Fig.4.22 “File” Node Composition.

● The “HTTP response” node is also used in this flow to send a response to requests from
the “HTTP IN” node.

4. The fourth flow consists of seven types of nodes:

The fourth flow is designed to compare each temperature measurement received from the
MQTT medium with the upper and lower temperature measurements defined by the user
in an automatic control CSV file for the previous flow. If the temperature measurement
value received from the MQTT media matches one of the values in the CSV file, the fan
will be controlled to start or stop according to the matching condition. The flow is shown
in Fig.4.23.

67
CHAPTER IV System Implementation and Outcomes

Fig.4.23 The Forth Flow.

● The “File in” node called “Temperature file by user” is used by the user to read the contents
of the file named "Temp_degree.csv" as a string. The composition of the node is shown in
Fig.4.24.

Fig.4.24 “File in” Node Composition.

68
CHAPTER IV System Implementation and Outcomes

● The node "Change" has two of them in this flow and they are used as in the third flow
where they are called "Set Temp_Max" and selects the high temperature variable and its
value from the message from the CSV file and "Set Temp_Min” sets the minimum
temperature variable and its value.

● The "Join" node where there are also two of them in this flow is called the first node
"Join_Temp_Max" is used to receive the incoming temperature from the MQTT broker
and the maximum temperature stored in the "Temp_degree.csv" file by the user and merge
it into an "Array". The second node called "Join_Temp_Min" is also used to receive the
temperature from the MQTT broker, and receive the minimum temperature value stored in
the “Temp_degree.csv” file, and merge it into an "Array".

● The flow has a "Function" node and both perform the same function, which is to test the
value received from the Mqtt broker for temperature with the control temperature values
stored by the user. Function_Max tests whether the incoming temperature value is greater
than or equal to the maximum temperature value specified by the user. If the condition is
met, a "ON" command is sent to the fan. If not, nothing will be sent, this is shown in
Fig.4.25. "Function_Min" tests if the incoming temperature value is less than or equal to
the minimum temperature value specified by the user or not. If the condition is met, a
"OFF" command is sent to the fan. If not, nothing will be sent, this is shown in Fig.4.26.

69
CHAPTER IV System Implementation and Outcomes

Fig.4.25 “Function” Node to turn on the fan.

Fig.4.26 “Function” Node to turn off the fan.

● The "MQTT Out" node is also the same in the second flow as it publishes the topic name
"Room/Fan" with the message that holds the status of the MQTT broker control on
localhost via port 1883 and then the MQTT broker sends it to the subscriber NodeMCU.

70
CHAPTER IV System Implementation and Outcomes

4.2.4 Frontend

Web-based interface (website) is designed and implemented to enable users to monitor the internal
environment and control the smart home devices via their smart device (phone/computer). SSMS
was used to create an SQL database containing data about the users and the smart home to be
displayed on the website. Visual Studio was used to create a website that connects to an SQL
database to verify users, allow them to enter the website, monitor temperature and humidity
through dashboards, and use ON/OFF buttons to control fan operation.

Smart Home website contains four main pages: Login, Dashboard, Automation, and Sittings.

A. Login Page
It is the first page displayed on the website as shown in Fig.4.27, where users can log in by
entering their data (email and password), and then verify it through users' data stored in the
SQL database.

Fig.4.27 Login page.

B. Dashboard Page
This page displays the dashboards that are shared by Grafana, as shown in Fig.4.28 Points
1 and 2 display temperature and 3 humidity.

71
CHAPTER IV System Implementation and Outcomes

Fig.4.28 Dashboard page.

Through HTTP API connection, the Grafana panel is accessed and shared as a link
embedded within the html code of the dashboard page as shown in Fig.4.29. Where the
link contains the URL of the Grafana panel.

Fig.4.29 Grafana panel URL

72
CHAPTER IV System Implementation and Outcomes

Point 3 in Fig.4.28, shows the fan ON/OFF switch, by pressing the "Save" button, the
command is sent to the Node-Red flow to be executed. In the HTML code of a Dashboard
page, the action attribute of a “Save” button element is used to specify where to send the
data (URL). URL Specifies the Node-Red flow address which contains the Node-Red
public IP address and the unique identifier for the flow as shown in Fig.4.30.

Fig.4.30 Node-Red flow URL.

C. Automation Page
The fan is turned ON/OFF in two ways, either directly from the user by pressing the
ON/OFF button from the dashboard page, or it turns automatically based on a certain
temperature.
The user can set these temperatures in the Automation page. As shown in point 1 in
Fig.4.31, the temperature is entered in the “ON” textbox, when this temperature is reached,
the fan turns on automatically. At point 2, the temperature is entered in the “OFF” text box,
when this temperature is reached, the fan turns off automatically.

Fig.4.31 Automation page

73
CHAPTER IV System Implementation and Outcomes

When temperature values are entered and the "Save" button is pressed, the data is sent to
Node-Red, where the Node Red flow URL is specified in the action attribute of the “Save”
button element in the HTML code of the Automation page.

D. Sittings Page

Sittings page as shown in Fig.4.32, that allows users to modify their data, and contact
admins to inquire or report if there is any problem.

Fig.4.32 Sittings page

4.3 System Validation and Outcomes

This section presents an example to validate the implementation of the system and the initial results
obtained in this system.

4.3.1 Temperature Monitoring

● The NodeMCU board is connected to the temperature and humidity sensor and the relay
module as in Fig. 4.33.

● The temperature and humidity are sensed every minute as shown in the NodeRed interface
in Fig.4.34.

74
CHAPTER IV System Implementation and Outcomes

Fig.4.33 Final shape of the NodeMCU board. Fig.4.34 NodeRed Dashboard.

● Fig.4.35 shows the temperatures displayed in NodeRed graphically on the user interface
for the same time period, in addition to the humidity degree displayed as in Fig.4.36.

Fig.4.35 Temperature Dashboard.

75
CHAPTER IV System Implementation and Outcomes

Fig.4.36 Humidity Dashboard.

4.3.2 Setting Temperature Thresholds


● In Fig.4.37 the temperature values are determined by the user interface automation page
by which the fan is turned on or off.

Fig.4.37 Setting Temperature Thresholds.

● Fig.4.38, shows user-entered values displayed on the NodeRed panel, where they are stored
in a CSV file. Also, the user can change the values as desired and they are saved in the
same csv file every time.

76
CHAPTER IV System Implementation and Outcomes

Fig.4.38 The temperature set by the user is displayed on the NodeRed interface.

4.3.3 Manual Control from the App


● The fan is turned on by pressing the On button on the Dashboard page of the user interface
as shown in Fig.4.39. When the fan is turned on, the user receives a notification of this as
shown in Fig.4.40.

Fig.4.39 Fan Switch is ON. Fig.4.40 SMS Notification.

● The fan was also turned off via the dashboard page of the user interface as shown in
Fig.4.41. When the fan is turned off; the user also receives a notification as shown in
Fig.4.42.

77
CHAPTER IV System Implementation and Outcomes

Fig.4.41 Fan Switch is OFF. Fig.4.42 SMS Notification.

4.3.4 Fan Automation


● As mentioned in Fig.4.37 the user-set temperatures to control the fan on-off states are 26°C
to turn off and 30°C to operate the fan. The "Fan Switch" node in Fig.4.43 shows that the
fan is on.

Fig.4.43 The Fun Switch is ON.

● Over time the temperature has changed, which was equal to 23°C "as shown in Fig.4.44
which is less than the value set to turn off the system, the system automatically turned off
the fan as shown in Fig.4.45 and send a notification to the user of the current temperature
and fan status as in the NodeRead panel in Fig.4.44. Fig.4.46 shows the SMS notification
received by the recipient.

78
CHAPTER IV System Implementation and Outcomes

Fig.4.44 NodeRed Dashboard. Fig.4.46 SMS Notification.

Fig.4.45 The Fan Switch is OFF

4.4 Summary

Several steps were applied to implement this system and obtain these results. This chapter aimed
to present the steps of creating the system through the backend interface by setting up the
Raspberry Pi and the NodeMCU boards and connecting them to the temperature sensor and the
fan. In addition, we have demonstrated the flows that have been applied to the Noderede platform
that enabled automated control of the fan. We have as well explained how the platform sends
notifications to the user in the event of a change in the fan’s condition as well. This chapter also
presented what had been implemented in the front-end of the system in terms of identifying the
pages of the site. Finally, the results obtained through the platform have been displayed.

79
CHAPTER V Conclusion and Future Work

CHAPTER 5
Conclusions and Future Work

80
CHAPTER V Conclusion and Future Work

5.1 Conclusions

In conclusion, this project presented a background of home automation systems that improve the
quality of life and provide comfort and safety for residents as well as saving energy. As these
systems can be implemented with many communication technologies such as WiFi, Zigbee, and
others, but after the emergence of the IoT in many domains, most notably smart homes, it has
become the most effective method, providing communication and interaction with home
appliances in real-time from anywhere in the world via the Internet.

Because of these advantages, this project provided the design and implementation of an IoT-based
home automation platform based on sensing indoor environmental conditions and controlling fan
operation automatically or via manual user control. And also The backend architecture of an IoT-
based home automation system and familiarization with all the tools. In addition to System
implementation steps in terms of setting up a Raspberry Pi and configuring Node-Red streams, as
well as obtained result in terms of automatic and manual control during the system test. This
system allows monitoring for data obtained from sensors (temperature and humidity) and control
of the fan automatically through the code built into Node-Red or manually through the web
interface via laptops/phones. Users can receive SMS notifications on their mobile phones about
any changes in the fan status, via the IFTTT server.

The results of this project are promising, and the developed system can increase users' safety and
convenience, and help reduce energy consumption as well as cost. The proposed system can be
expanded with additional sensors and actuators to make it more convenient and efficient in the
future.

5.2 Future Work

The future work can be divided as follows:


● Study the implementation of security on the system.
● Adding more sensors and devices to the system to implement various functions in the home
automatically.
● Develop a mobile application for the system to improve the accessibility of the system.

81
References

References
[1] Waheb A. Jabbar, Tee Kok Kian, Roshahliza M. Ramli, Siti Nabila Zubir, Nurthaqifah S. M.
Zamrizaman, Mohammed Balfaqih, Vladimir Shepelev, and Soltan Alharbi. "design and
fabrication of smart home with internet of things enabled automation system". “IEEE Access”, 7,
2019.
[2] Jawaher A. Fadhil, Omar A. Omar and Qusay I. Sarhan. "A Survey on the Applications of
Smart Home Systems". In 2020 “International Conference on Computer Science and Software
Engineering (CSASE)”,pages 168-173 ,2020.
[3] Waheb A. Jabbar, Mohammed H. Alsibai, Nur S. S. Amran, and Samiah K. Mahayadin.
"Design and Implementation of IoT-Based Automation System for Smart Home". In 2018
“International Symposium on Networks, Computers and Communications (ISNCC)”, pages 1–6,
2018.
[4] Muhammad Asadullah and Ahsan Raza. "An overview of home automation systems" . In 2016
2nd “International Conference on Robotics and Artificial Intelligence (ICRAI)”, pages 27-31,
2016.
[5] R. Sivapriyan, K. M. Rao and M. Harijyothi. "Literature Review of IoT based Home
Automation System". In 2020 Fourth “International Conference on Inventive Systems and Control
(ICISC)”,pages 101-105, 2020.
[6] D. Nawara and R. Kashef. "IoT-based Recommendation Systems – An Overview". In 2020
“IEEE International IOT, Electronics and Mechatronics Conference (IEMTRONICS)”, pages 1-7,
2020.
[7] S. R. J. Ramson, S. Vishnu and M. Shanmugam. "Applications of Internet of Things (IoT) – An
Overview". In 2020 5th “International Conference on Devices, Circuits and Systems (ICDCS)”,
pages 92-95, 2020.
[8] N. H. Motlagh, S. H. Khajavi, A. Jaribion and J. Holmstrom. "An IoT-based automation system
for older homes: a use case for lighting system". In 2018 “IEEE 11th Conference on Service-
Oriented Computing and Applications (SOCA)”, pages 1-6, 2018.
[9] J. Ding, M. Nemati, C. Ranaweera and J. Choi. "IoT Connectivity Technologies and
Applications: A Survey". In “arXiv preprint arXiv:2002.12646”, 2020.

82
References

[10] S. Al-Sarawi, M. Anbar, K. Alieyan and M. Alzubaidi, "Internet of Things (IoT)


communication protocols: Review". In 2017 8th “International Conference on Information
Technology (ICIT)”, pages. 685-690, 2017.
[11] Nasar, Mohammad and Abu Kausar, Mohammad. “Suitability Of Influxdb Database For IoT
Applications”, (2019).
[12] Rautmare, Sharvari and Dipashree M. Bhalerao. “MySQL and NoSQL database comparison
for IoT application”. In 2016 IEEE “International Conference on Advances in Computer
Applications (ICACA)” , 2016.
[13] R. Maurya, K. A. Nambiar, P. Babbe, J. P. Kalokhe, Y. S. Ingle and N. F. Shaikh .
“Application of Restful APIs in IOT: A Review". In “International Journal for Research in Applied
Science & Engineering Technology (IJRASET)”, 2021.
[14] Geoffrey C. Fox, Supun Kamburugamuve and Ryan D. Hartman, "Architecture and measured
characteristics of a cloud based internet of things". In 2012 “International Conference on
Collaboration Technologies and Systems (CTS)”, pages. 6-12, 2012.
[15] Sahar S. Tabrizi and Dogan Ibrahim. “A Review on Cloud Computing and Internet of Things“.
In “International Journal of Computer and Information Engineering”, 2017.
[16] Wiam Y. AL Hayek and Rasha A. A. ODEH. ”Cloud ERP VS On-Premise ERP”, In
“International Journal of Applied 10.4”, 2020.
[17] Somphop Chanthakit and Choopan Rattanapoka. "MQTT Based Air Quality Monitoring
System using Node MCU and Node-RED". In 2018 Seventh “ICT International Student Project
Conference (ICT-ISPC)”, pages 1-5, 2018.
[18] Sourabh Sarkar, S. Gayen and Srijita Bilgaiyan. "Android Based Home Security Systems
Using Internet of Things(IoT) and Firebase". In 2018 “International Conference on Inventive
Research in Computing Applications (ICIRCA)”, pages 102-105, 2018.
[19] Satyendra K. Vishwakarma, Prashant Upadhyaya, Babita Kumari and Arun K. Mishra.
"Smart Energy Efficient Home Automation System Using IoT" . in 2019 4th “International
Conference on Internet of Things: Smart Innovation and Usages (IoT-SIU)”, pages 1-4, 2019.
[20] Neven Nikolov and Ognyan Nakov. "Research of Secure Communication of Esp32 IoT
Embedded System to.NET Core Cloud Structure using MQTTS SSL/TLS". In 2019 “IEEE XXVIII
International Scientific Conference Electronics (ET)”, pages 1-4, 2019.

83
References

[21] Santhi Venkatraman, R. R. Varshaa and P. Vigneshwary."IoT based Door open or close
monitoring for home security with emergency notification system using LoRa Technology". In
2021 7th “International Conference on Advanced Computing and Communication Systems
(ICACCS)”, pages 173-178, 2021.
[22] Paul Macheso, Tiwonge D. Manda, Sylvester Chisale, Nelson Dzupire, Justice Mlatho and
Didacienne Mukanyiligira. "Design of ESP8266 Smart Home Using MQTT and Node-RED". In
2021 “International Conference on Artificial Intelligence and Smart Systems (ICAIS)”, pages 502-
505, 2021.
[23] Punit Gupta and Jasmeet Chhabra. "iot based smart home design using power and security
management". In 2016 “International Conference on Innovation and Challenges in Cyber Security
(ICICCS-INBUSH)”, pages 6–10, 2016.
[24] DHT11 Technical Datasheet, available online:
https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-
1143054.pdf
[25] Erwin Ouyang. ”Hands-On-ESP8266-Mastering-Basic-Peripherals.pdf”, October 2018.
[26] Somesh Kuma Aditee Mattoo. “Internet of Things: A Progressive Case Study”. In “Handbook
of IoT and Big Data. CRC Press”, 2019.
[27] "ESP8266 NodeMCU Relay Module - Control AC Appliances (Web Server) | Random Nerd
Tutorials", in “Random Nerd Tutorials”, 2022. [Online]. Available:
https://randomnerdtutorials.com/esp8266-relay-module-ac-web-
server/#:~:text=There%20are%20relay%20modules%20whose,or%20the%203.3V%20pin .
[28] "What is a Raspberry Pi?", in “Raspberry Pi”, 2022. [Online]. Available:
https://www.raspberrypi.org/help/what-%20is-a-raspberry-pi .
[29] Boban Davidovic and Aleksandra Labus. "a smart home system based on sensor technology".
In “Facta universitatis - series: Electronics and Energetics”, 2016.
[30] “Node RED Programming Guide – Programming the IoT", in “Noderedguide.com”, 2022.
[Online]. Available: http://noderedguide.com/ .
[31] "Node-RED", in “Nodered.org”, 2022. [Online]. Available: https://nodered.org .
[32] Choopan Rattanapoka, Somphop Chanthakit, Apatsaraporn Chimchai, and Amorntip
Sookkeaw. "an mqtt-based iot cloud platform with flow design by node-red". In 2019 “Research,
Invention, and Innovation Congress (RI2C)”, pages 1–6, 2019.

84
References

[33] Milica Lekić and Gordana Gardašević. "IoT sensor integration to Node-RED platform". In
2018 17th “International Symposium INFOTEH-JAHORINA (INFOTEH)” , pages 1-5, 2018.
[34] G. Gardasevic, H. Fotouhi, I. Tomasic, M. Vahabi, M. Bjorkman and M. Linden. “A
Heterogeneous IoT-based Architecture for Remote Monitoring of Physiological and
Environmental Parameters”. In 4th “EAI International Conference on IoT Technologies for
HealthCare, Angers, France”, 2017.
[35] Ravi K. Kodali and SreeRamya Soratkal. "MQTT based home automation system using
ESP8266 ''. In 2016 “IEEE Region 10 Humanitarian Technology Conference (R10-HTC)”, pages
1-5, 2016.
[36] Biswajeeban Mishra and Attila Kertesz. "The Use of MQTT in M2M and IoT Systems: A
Survey," in IEEE Access”, 2020.
[37] Ravi .Kishore Kodali and Arshiya Anjum. "iot based home automation using node-red". In
2018 “Second International Conference on Green Computing and Internet of Things (ICGCIoT)”,
pages 386–390, 2018.
[38] Sunil Kumar .H and Saravanan C. “A Comprehensive study on Data Visualization tool -
Grafana”. In “Jetir.org”, 2022. [Online]. Available:
https://www.jetir.org/view?paper=JETIR2105788. [Accessed: 12- Apr- 2022].

[39] Syeda Naqvi, Sofia Yfantidou, and Esteban Zimányi. "Time Series Databases and InfluxDB".
In “Studienarbeit, Université Libre de Bruxelles 12 “, 2017.
[40] "Grafana", in “ InfluxData”, 2022. [Online]. Available:
https://www.influxdata.com/partners/grafana/ [Accessed 8- Apr- 2022].
[41] "SQL Server Management Studio (SSMS) - SQL Server Management Studio (SSMS)", in
“Docs.microsoft.com”, 2022. [Online]. Available: https://docs.microsoft.com/en-us/sql/ssms/sql-
server-management-studio-ssms?view=sql-server-ver15 [Accessed: 3- March- 2022].
[42] Anthony Nokrach. “Comparing the databases MSSQL and MongoDB for the web-based
environment Ozlab” , 2018.
[43] "Overview of Visual Studio", in “Docs.microsoft.com”, 2022. [Online]. Available:
https://docs.microsoft.com/en-us/visualstudio/get-started/visual-studio-ide?view=vs-2022.
[Accessed: 12- Apr- 2022].

85
References

[44] Philip Conrod and Lou Tylee. “VISUAL C# AND DATABASES “. 2017 Ed. In “Kidware
Software LLC”, 2017.
[45] Boban Davidovic and Aleksandra Labus. ”A smart home system based on sensor technology”.
In “Facta Universitatis, Series: Electronics and Energetics”, 2016.
[46] "Raspberry Pi Documentation - Getting Started", in “Raspberrypi.com”, 2022. [Online].
Available: https://www.raspberrypi.com/documentation/computers/getting-started.html.
[47] "Raspberry Pi Documentation - Configuration", in “Raspberrypi.com”, 2022. [Online].
Available: https://www.raspberrypi.com/documentation/computers/configuration.html.
[48] "ESP8266: General Information & Specifications - ESP8266 Shop", in "ESP8266 Shop",
2022. [Online]. Available: https://esp8266-shop.com/esp8266-guide/esp8266-information/.

86
Appendix

A. Appendix

A.1 Preparing the Raspberry Pi

A.1.1 Installation of OS on raspberry pi use raspberry pi imager


● First, connect the SD card reader to the SD card inside and connect it to the
computer.
● Secondly, open the Raspberry Pi Imager. Choose “CHOOSE OS” ,then a
menu will appear for you to choose the desired operating system from the
displayed list.
● Third, choose “CHOOSE STORAGE” to select the SD card you want to
write to.
● Finally, click the "Write" button to write data to the SD card[46].

Fig.A.1 Connect the SD card to Computer.

87
Appendix

A.1.2 Connect raspberry pi to network via wifi


There are several ways to connect a Raspberry Pi to a network. One of them is the
wpa_supplicant file method that was used in this project.
● First, use any text editor (like notepad) and create a file called
"wpa_supplicant" to set up raspberry pi wifi.

● Second, copy the following code into wpa_supplicant file, then type
the network address in the ssid field and the password in the psk
field.

● Third, save the file to the SD card in the boot partition.


➢ This file will keep your WiFi credentials and will
automatically connect the raspberry pi to the network when
you turn it on.

● Finally, activate SSH by creating an empty file called SSH in the


boot partition without any extension. It is to interact with the
raspberry pi command line.
Now you can access the command line remotely by ssh using Putty software.

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=<Insert 2 letter ISO 3166-1 country code here>
network={
ssid="yourHiddenSSID"
scan_ssid=1
psk="**********"
}

88
Appendix

After the Raspberry Pi is set up and set up to connect to the network via Wi-Fi, an SD card is
connected to the Raspberry Pi. Then the network address is written in the ssid field and the
password in the psk field. You can now access the command line remotely via ssh using Putty.

A.1.3 The commands to install InfluxDB are as follows

sudo apt-get update && sudo apt-get install influxdb


sudo apt install influxdb-client
create database name

A.1.4 The commands to install Mosquitto Broker are as follows

sudo apt-get install mosquitto -y


sudo apt-get install mosquitto-clients

A.1.5 The commands to install Node-red Broker are as follows

Sudo apt-get install node red


Sudo apt-get install npm
node-red-start

A.2 NodeMCU Specifications

All ESP8266 variants have a ESP8266EX core processor and a Tensilica L106 32-bit micro
controller unit. Wireless SoC (System-On-Chip). It provides capabilities for 2.4 GHz Wi-Fi
(802.11 b/g/n, supporting WPA/WPA2), general-purpose input/output (13 GPIO), Inter-Integrated
Circuit (I²C), analog-to-digital conversion (10-bit ADC), Serial Peripheral Interface (SPI), I²S
interfaces with DMA (sharing pins with GPIO), UART (on dedicated pins, plus a transmit-only
UART can be enabled on GPIO2), and pulse-width modulation (PWM) [48].
It has a build-in programmer and a voltage regulator, that allow flashing and powering the device
via micro-USB. The system operates at 3.3V [48].
Here is an overview of the ESP8266 NodeMCU’s specifications [48]:

89
Appendix

 Tensilica L106 32-bit micro controller unit at 80 MHz (or overclocked to 160 MHz)
 32 kB instruction RAM
 80 kB user data RAM
 16 kB ETS system data RAM
 Flash Memory 4Mb
 USB – micro USB port for power, programming and debugging
 13 GPIO pins
 802.11 b/g/n, supporting WPA/WPA2
 STA / AP modes support
 TCP / IP protocol stack, One socket
 TCP / UDP Server and Client
 Serial port baud rate configuration:
1200/2400/4800/9600/19200/38400/57600/74800/115200 bps
 Pin-compatible with Arduino UNO, Mega
 KEY button: modes configuration
 32-bit hardware timer
 WiFi operation current: continuous transmission operation: ≈70mA (200mA MAX), deep
sleep mode: <3mA
 Serial WiFi transmission rate: 110-460800bps
 Temperature: -40℃ ~ + 125 ℃
 Humidity: 10%-90% non-condensing
 Weight: about 20g (0.7oz)
 Pulse-Width Modulation (PWM)
 Interrupt capability
 3.3V operating voltage, internal voltage regulator allows 5V on power input
 maximum current through GPIO pins: 12mA (source), 20mA (drain)
 available firmware for Arduino IDE
 Websocket libraries available.

90
Appendix

A.3 Preparing the NodeMCU

A.3.1 Connect NodeMCU network via wifi


The NodeMCU board consists of an ESP8266 chip. It is a low cost WiFi chip. Before we
can program and connect the NodeMCU to wifi, we need to connect the NodeMCU to the
computer. This is explained in the following steps:

● First, connect the Node-MCU to the computer via USB port.


● Secondly, open the device manager to find the COM port of NodeMCU as shown
in Fig.7.2.

Fig.A.2 Device Manager.


After connecting the Node-MCU to your computer, you can now access the Wi-Fi network.
In this project the Arduino IDE was used to program the ESP8266. The ESP8266 library
is not included in the Arduino IDE, so you have to install it manually, the following steps
on how to install the ESP8266 library:
1. Start Arduino IDE, go to File menu, and open the Preferences window.

91
Appendix

2. Enter“http://arduino.esp8266.com/stable/package_esp8266com_index.json”
into Additional Board Manager URLs field as shown in Fig.A.3..
3. Go to Tools → Board menu, open Boards Manager, and install esp8266 platform.
4. After installation, select the NodeMCU 1.0 (ESP-12E Module) board from Tools
→ Board menu as shown in Fig.A.4.

With the ESP8266 library installed, the Node-MCU can now be programmed, written
commands, and given a network name and address to connect to, using a C++ language.

Fig.A.3 Enter the ESP8266 library into Additional Board Manager URLs field.

92
Appendix

Fig.A.4 Install the ESP8266 library.

After installing the ESP8266 library in the Arduino IDE it is included inside the code as
well as the network name and password.

Fig.A.5 Included the ESP8266 library in the Arduino IDE.

93
Appendix

A.4 The Arduino Code

#include <sstream>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"

#define DHTTYPE DHT11 // DHT 11


//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

// Change the credentials below, so your ESP8266 connects to your router


const char* ssid = "SmartCom4G";
const char* password = "M35713442";
int Z=0;
float old_hum=0;
float old_temp=0;
// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "192.168.1.105";

// Initializes the espClient. You should change the espClient name if you have multiple ESPs
running in your home automation system
WiFiClient espClient;
PubSubClient client(espClient);

// DHT Sensor - GPIO 13 = D7 on ESP-12E NodeMCU board


const int DHTPin = 13;

// Lamp - LED - GPIO 5 = D1 on ESP-12E NodeMCU board


const int lamp = 5;

// Initialize DHT sensor.


DHT dht(DHTPin, DHTTYPE);

// Timers auxiliar variables


long now = millis();
long lastMeasure = 0;
long last=0;
// Don't change the function below. This functions connects your ESP8266 to your router
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

94
Appendix

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}

// This functions is executed when some device publishes a message to a topic that your
ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a
message to a topic that
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;

for (int i = 0; i < length; i++) {


Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();

// Feel free to add more if statements to control more GPIOs with MQTT

// If a message is received on the topic room/lamp, you check if the message is either on or
off. Turns the lamp GPIO according to the message
if(topic=="room/lamp"){
Serial.print("Changing Room lamp to ");
if(messageTemp == "on"){
digitalWrite(lamp, HIGH);
Serial.print("On");
}
else if(messageTemp == "off"){
digitalWrite(lamp, LOW);
Serial.print("Off");
}
}
Serial.println();
}

95
Appendix

// This functions reconnects your ESP8266 to your MQTT broker


// Change the function below if you want to subscribe to more topics with your ESP8266
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect

if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("room/lamp");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

// The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a
baud rate of 115200
// Sets your mqtt broker and sets the callback function
// The callback function is what receives messages and actually controls the LEDs
void setup() {
pinMode(lamp, OUTPUT);

dht.begin();

Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);

// For this project, you don't need to change anything in the loop function. Basically it ensures
that you ESP is connected to your broker
void loop() {

if (!client.connected()) {

96
Appendix

reconnect();
}
if(!client.loop())
client.connect("ESP8266Client");

now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 30000) {
lastMeasure = now;

// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Computes temperature values in Celsius


float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(hic, 6, 2, temperatureTemp);

// Uncomment to compute temperature values in Fahrenheit


// float hif = dht.computeHeatIndex(f, h);
// static char temperatureTemp[7];
// dtostrf(hif, 6, 2, temperatureTemp);

static char humidityTemp[7];


dtostrf(h, 6, 2, humidityTemp);
if(Z==0){
// Publishes Temperature and Humidity values
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);

97
Appendix

Serial.print(" *F\t Heat index: ");


Serial.print(hic);
Serial.println(" *C ");
// Serial.print(hif);
// Serial.println(" *F");
Z++;
old_hum=h;
old_temp=t;
}
if(Z!=0){
if(h-old_hum > 1.0 || h-old_hum < -1.0 || t-old_temp > 1.0 || t-old_temp < -1.0)
{
old_temp=t;
old_hum = h;
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");

}
if(now - last > 60000)
{
last=now;
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
}

98
Appendix

}
}

99

You might also like