You are on page 1of 51

Smart Home System

Chapter 1
INTRODUCTION

1
Smart Home System

1.1. Overview

Smart Home System is the automation of house hold activities. This includes centralized
control of lighting, Heavy Voltage AC Loads (heating, ventilation, air conditioning etc.) to
provide improved convenience, comfort, energy efficiency and security. In clearly to say Home
Automation concept has existed for many years. But the terms Smart Home, Intelligent Home
means the introduction of concepts of networking appliances and devices in the house.
Automation involves the use of control systems and information technologies to reduce the
human efforts to do a job. It provides intelligence, comfort and improved quality of life like
offering powerful means of helping and supporting special needs of elderly and people with
disabilities and monitoring the environments.

Present days, in our homes, we are controlling every electrical appliance by using switches
which are installed on the wall. This is old style. Now try to thick about the new style that I am
trying to achieve by means of this project. All switches at your finger tip to switch it on or off,
whether you are in home or in remote area. It is very amazing, is not it? Now, thick about its
advantages over the old styled wall built switches. Switching on or off all lights or fan by sitting
in one place, opening or closing doors, SMS or emails alerts of house status such as intrusion
detections, gas or fire detections etc. and taking a response action of it, while you are outside of
the house, makes us very protective about our homes. This kind of new style provides us safety
and security from every incident that happens in home. This system is also very helpful in case
of supporting elderly, people with disabilities and even keeping an eye on children. In this way,
our project provides the convenience, security, entertainments, and even power savings leading
to better quality of life.

Now a days, there is an attractive market for home automation and networking. For example,
IOTs. Internet Of Things (IOT) connects everyday objects to Internet. It creates new dimensions
to the world of information and communication technologies. It also provides the advancement
of leading to anyone, anytime, anywhere (AAA).

Coming to the Smart Home System implementation details, the overall system consist of
both hardware and software. The total system works based on microcontroller. Microcontroller is
the heart of the total hardware, connected to all electrical appliances in the home.

1.2. About the Project

Now you know, what is our project Smart Home System, its advantages, etc. And another question
which comes to our mind is how to implement this system. For this system we have to go a little bit
deeper into the project. The overall idea of this project is to switch a particular device on or off by using a
software. The software may be in a laptop or in a smart phone. So, there is a need of both hardware and
software to be used in this system.

2
Smart Home System

Coming to hardware, the main parts or components, which we require is a micro-controller


(which accepts the requests from the software), and electrical devices (which we want to control) and a
bridge between these two things i.e. a Relay or Triac.

And in the software part, the code or program that communicates with the hardware and a user
free interface to interact the user with the software that we are developing. In the software side, the main
functionalities are given below.

First, the users needs to login to the software, by using username and password in a secure way. Here
in this project, we are using both the computer and a smart phone as clients to interact with the heart of
the hardware i.e. micro-controller. So, in the both interfaces for a computer or a smart phone, we require
login pages.

After the successful login of the SHS, getting information of the total devices installed in a house and
their switch details. By using these details, a user friendly interface to switch those devices with their
status is needed. And then, logout.

If we are using any sensors in the hardware means, its implementation also required in the software,
so the users can be informed.

Coming to the users, there three kind of users we are dealing with. First, the owners of the house i.e.
root having all kind of full powers over all devices like switching on or off, locking a particular switch so
the other user wont use it etc. Next, the other users are the normal members of the house and in extreme
cases guest. So, the user interface must be user friendly to be used.

1.3. Purpose

As we have already mentioned that the whole purpose is to switch on or off the house hold devices by
using app. The app must be user friendly. It may be a System application or smart phone application. This
app can be used by anyone, any time, and anywhere, like outside the house, remote areas, etc.

1.4. Scope

Coming to Scope of this project, this is an ongoing project. This project gives basic idea of how to
control various home appliances and provide a security using Android phone/tab. Based on this idea, the
various systems like home automation, surveillance system, entertainments, and even complete smart
home automation in which the system can operates itself on its own. In this type of advanced systems,
concepts like digital image processing, artificial intelligence, etc. can be used. Our project, being a basic
project, gives the most basic information about home automation technology, which is very helpful in
implementing any king of complex system.

3
Smart Home System

Chapter 2
SYSTEM ANALYSIS

4
Smart Home System

2.1. Present System

Coming to the 21st century, with the growth in the Technology and Intelligence to the
newer limits, things are becoming simpler and easier for us to maintain. And the electronic
devices such as smart phones, computers etc. became a part of our day to day activities. Among
these, Home automation is also one, which allows us to control house hold appliances like lights,
fans, doors, AC etc. The home automation technology is an ongoing project, which is under
development. Because of the lack of standards for development and maintenance, cost of such
type of home automation systems in the present market, availability of the resources to make it
work, etc. the thought of using and implementing home automation project is only now limited
to the rich people, who can buy them. But coming to the normal person, this technology still
remained as a dream. And also the complications such as implementing this kind of projects
differ house to house, because of the house constructions. Another important point to be noted is
this home automation system involves hardware like wiring to be done to each electrical device
at time of house construction. So, these kind of integrations need to be planned in advance. And
also these are also difficult to upgrade or replace once installed. This kind of complexities,
makes overall home automation systems to a bit more difficult to implement and overall cost of
this work clearly is out of the normal persons view.

And also most commercially available home automation systems are all-in-one solutions
which require that all controllable appliances are from the same company or must be approved as
compatible with said companys system. Moreover these systems normally come with a
proprietary, dedicated device which acts as the control center. To control the system from
multiple locations, additional control devices must be purchased.

2.2. Proposed System

Coming to the persent technology point of view, because of the growth in technology, the
devices like computers, smartphones, iPods, etc. are now available to cheaper cost. This is the
one of the advantage of the home automation systems. Every normal person is carrying a smart
phone or a laptop with him. These devices come with inbuilt Bluetooth, Wi-Fi modules, which
decreases the overall system cost to implement. Then the user only left to concentrate on the
hardware part. In the hardware side of this project, all the user needs is a microcontroller to
operate, heavy voltage handling devices such as Relays or Triacs and to communicate with the
micro controller by using cellphone or laptop, a communication medium such as Bluetooth or
Wi-Fi module is required. And then the software, which needs to be most user friendly, is the
one and only requirement from software side. These days, these kinds of software, all are
available on internet. So, the proper planning of designing is the only concern part to the
designer. These systems with the simplified design, can be easily integrated into an existing
electrical system of a building. It can also be easily installed for just a single room if one so

5
Smart Home System

desires. Modifications to the existing electrical system are minimal, thereby reducing
installations costs.

2.3. Benefits of the System

Benefits or advantages of this system are numerous. Some of them are listed below.

Most user friendly interface, so everyone can handle it.


Switching on or off all devices anywhere and anytime.
Support for elderly and physically disabled people
Fire or gas detections and taking response actions Safety
Intrusion detections helps in case of thefts Security
Automatic environmental control Convenience
Surveillance and Security
Avoiding unnecessary lights/heat etc. Energy saving
Entertainment controlling etc.
Reduces human efforts to a job.

6
Smart Home System

Chapter 3
SPECIFIC REQUIREMENTS

7
Smart Home System

3.1. Software Requirements

Arduino IDE for microcontroller programming


Eclipse/NetBeans IDE for java or android application programming
RXTX Java Library for Serial Communication (UART) protocol use

3.2. Hardware Requirements

Arduino Uno or Mega 2560 basic open source microcontroller, easy to program in C++
Wi-Fi Module
Relay or Triac Board

3.3. Functional Requirements

As a basic home automation project, the main functionality is to switch on or a particular device
using app. And also secondary functional requirements are mentioned in here.

User should be able to switch on or off a particular device


Support for three different kind of users
o Root having full control over the SHS, activities such as switching on or off,
locking particular switch from user access, new user registrations, blocking them,
updating etc.
o Normal user Switch off or on a device over app, changing user details like
passwords etc.
o Guest able to switch on or off a device by means of manual push buttons
installed in the house walls, but not through the app on smart phone or laptop
Locking mechanism locking a particular switch by root in order to maintain the user
safety.
All switch status representation in the app so the user can freely interact with the system.
Support for long range in which the app should be used or the medium we use to
communicate with the SHS like Bluetooth, WIFI, X10 or Ethernet etc.

3.4. Non Functional Requirements

Interface:
This project SHS is an application, which directly deals with the users. So there is the need of most user
friendly interface. The medium for this user friendliness is the app. For the app development, for the
laptop use, Java programming is used. And coming to the smart phone, android programming is used.
These tools make the best use of application by the end users.

8
Smart Home System

Communication Interfaces:
The user should be able to operate the app or having the connectivity to the app while he is in remote
areas. There is a need of proper communication medium requirement like Bluetooth or Wi-Fi etc.
Otherwise connectivity to Ethernet also provides proper communication to the hardware.

Reliability:
User should get the appropriate response for his request to the micro controller. In microcontroller, C++
programming is used. And in the app, java or android programming is used. From app to micro controller
the requests are to be sent. And in response, after performing the intended task the response is received
from the micro controller. So there is a need of proper control and management over requests and their
response. These can be achieved my means of proper programming.

System Availability:
If we are using Wi-Fi technology in our project, means that the inbuilt server in the Wi-Fi module is used
for communication. It should be available to connect for all time in the range. All programming error,
which makes the server to crash, must be eliminated in programming designing.

Performance:
Along with the user friendly interface, the SHS should be providing the quick response to the user in
order to make them feel free to interact with the system. Here the performance is based on the logics
designed during the implementation stage. So in order to achieve the performance, best logics must be
used in the programming.

Safety:
For every wireless application, there is a need of Security from unauthorized intruders. Especially in this
world of technologies, there is a big need of perfect systems with no vulnerabilities. As it is a Wi-Fi based
application, the confidential details such as username and passwords and even server details must be kept
secret. So, all kind of restrictions and satisfying conditions to be made in the programming to avoid
unauthorized access to the SHS.

Extensibility:
Being a home automation system, this SHS must be capable of extending because of the growth in the
technology. New features must be adapted. For this, the need of following the standards of present
marketing products must be done.

9
Smart Home System

Chapter 4
SYSTEM DESIGN

10
Smart Home System

This Smart Home System is a home automation project. So, there is need of development
of both the hardware and software. The overall implementation of them is as follows.

4.1. Hardware Development

In hardware part, the main requirements are microcontroller, the heart of the SHS, the
electrical loads which we want to control and the driving circuit such as relay or triac board.

Coming to the microcontroller, we used Arduino Uno microcontroller board, which is


based on ATmega328. It contains 14 digital input pins in which, 2 of them used for serial
communication for USB. Remaining pins can be programmed to switch on or off the loads by
driving the triac circuit, we are using. In Arduino Uno microcontroller, the programming used is
C++. So, by using C++ programming, we can set a particular pin among the 14 digital pins to
HIGH i.e. 5 volts. If we are setting LOW, means that we are providing 0 volt through that pin.
So, we can control the pins by setting HIGH or LOW to them.

Electrical loads we are using are capable of 230 volts. This much of voltage is not
generated by the microcontroller. So we need some kind of bridge between 5 volts to 230 volts,
which takes 5 volts i.e. HIGH as input and switches ON 230 volts Load such as bulb for
example. Here this bridge is Triac circuit.

Overall Implementation Diagram is given below.

11
Smart Home System

Arduino Uno Specifications:

Microcontroller ATmega328
Operating Voltage 5V
Input Voltage
7-12V
(recommended)
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA
Flash Memory 32 KB (ATmega328) of which 0.5 KB used by boot loader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Clock Speed 16 MHz

Triac Circuit:

The following circuit is the triac circuit, which we used to control the Home appliances
by the microcontroller. This circuit has mainly optocoupler and traic.

Fig. 4.1.1

Optocoupler is the driver for the Triac. Optocoupler provide electrical isolation between
an input source and an output load. When we give the 5V pulse to the pin 1 then the LED that
produces infra-red light, a semiconductor photo-sensitive device that detects the emitted infra-red
beam and conduct the current. Because of this flow of high current then Triac get in conduction
and light will glow.

12
Smart Home System

The flow of current during the positive cycle is in the direction as shown in the fig. 4.1.2

Fig. 4.1.2

The flow of current during the negative cycle is in the direction as shown in the fig. 4.1.3

Fig. 4.1.3

Optocoupler
Optocoupler provide electrical isolation between an input source and an output load.
An Optocoupler, also known as an Optoisolator or Photocoupler, is an electronic component that
interconnects two separate electrical circuits by means of a light sensitive optical Interface.

The basic design of the optocoupler consists of an LED that produces infra-red light and
a semiconductor photo-sensitive device that is used to detect the emitted infra-red beam. Both
the LED and photo-sensitive device are enclosed in a light-tight body or package with metal legs
for the electrical connections as shown.

13
Smart Home System

An optocoupler or opto-isolator consists of a light emitter, the LED and a light sensitive
receiver which can be a single photo-diode, photo-transistor, photo-resistor, photo-SCR, or a
photo-TRIAC.

Phototransistor Optocoupler
Assume a photo-transitor device as shown in fig. 4.2.1.Curent from the source signal
passes through the input LED which emits an infra-red light whose intensity is proportional to
the electrical signal.

Fig. 4.2.1

This emitted light falls upon the base of the photo-transistor, causing it to switch-ON and
conduct in a similar way to a normal bipolar transistor.

When the current flowing through the LED is interrupted, the infra-red emitted light is
cut-off, causing the photo-transistor to cease conducting. The photo-transistor can be used to
switch current in the output circuit. The spectral response of the LED and the photo-sensitive
device are closely matched being separated by a transparent medium such as glass, plastic or air.
Since there is no direct electrical connection between the input and output of an optocoupler,
electrical isolation up to 10kV is achieved.

Optocouplers are available in four types, each one having an infra-red LED source but
with different photo-sensitive devices.

OPTOCOUPLER TYPES
The four optocouplers are
1) Photo - transistor,
2) Photo - darlington,
3) Photo SCR and
4) Photo - Triac as show in fig. 4.2.2.

Fig. 4.2.2
14
Smart Home System

The photo-transistor and photo -darlington devices are mainly for use in DC circuits while the
photo-SCR and photo- Triac allow AC powered circuits to be controlled.

OPTOCOUPLER APPLICATIONS:

Optocouplers and opto-isolators can be used on their own, or to switch a range of other
larger electronic devices such as transistors and Triacs providing the required electrical isolation
between a lower voltage control signal and the higher voltage or current output signal. Common
applications for optocouplers include microprocessor input/output switching, DC and AC power
control, PC communication, signal isolation and power supply regulation which suffer from
current group loops, etc..

TRIAC OPTOCOUPLER APPLICATION

Fig. 4.2.3

This type of optocoupler configuration forms the basis of a very simple solid state relay
application which can be used to control any AC mains powered load such as lamps and motors.
Also unlike a thyristor (SCR), a Triac is capable of conducting in both halves of the mains AC
cycle with zero-crossing detection allowing the load to receive full power without the heavy
inrush currents when switching inductive loads.

Triac

A Triac is a three-terminal semiconductor switching device which can control alternating


current in a load. A Triac is mainly constructed by using the two SCRs.

The major drawback of an SCR is that it can conduct current in one direction only.
Therefore, an SCR can only control d.c. power or forward biased half-cycles of a.c. in a load.
However, in an a.c. system, it is often desirable and necessary to exercise control over both
positive and negative half-cycles. For this purpose, a semiconductor device called Triac is used.

Triac is an abbreviation for triode a.c switch. Tri indicates that the device has three terminals
and ac means that the device controls alternating current or can conduct current in either

15
Smart Home System

direction. Since a Triac can control conduction of both positive and negative half-cycles of a.c.
supply, it is sometimes called a bidirectional semi-conductor triode switch.

TRIAC CONSTRUCTION

A Triac is a three-terminal, five-layer semiconductor device whose forward and reverse


characteristics are identical to the forward characteristics of the SCR. The three terminals are
designated as main terminal MT1, main terminal MT2 and gate G.

Below Diagram show the Construction of the Triac with the SRCs.....

Fig. 4.3.1
Fig. 4.3.1 (i) shows the basic structure of a Triac. As we shall see, a Triac is equivalent to
two separate SCRs connected in inverse parallel (i.e. anode of each connected to the cathode of
the other) with gates commoned as shown in Fig. 3.1(ii). Therefore, a Triac acts like a
bidirectional switch i.e.it can conduct current in either direction. This is unlike an SCR which
can conduct current only in one direction. Fig. 3.1 (iii) shows the schematic symbol of a Triac.
The symbol consists of two parallel diodes connected in opposite directions with a single gate
lead. It can be seen that even the symbol of Triac indicates that it can conduct
current for either polarity of the main terminals (MT1 and MT2) i.e. it can act as a bidirectional
switch. The gate provides control over conduction in either direction.
The following points many be noted about the Triac:

(i) The Triac can conduct current (of course with proper gate current) regardless of the
polarities of the main terminals MT1 and MT2. Since there is no longer a specific
anode or cathode, the main leads are referred to as MT1 and MT2.

(ii) A Triac can be turned on either with a positive or negative voltage at the gate of the
device.

16
Smart Home System

(iii) Like the SCR, once the Triac is fired into conduction, the gate loses all control. The
Triac can be turned off by reducing the circuit current to the value of holding current.

(iv) The main disadvantage of Triacs over SCRs is that Triacs have considerably lower
current-handling capabilities. Most Triacs are available in ratings of less than 40A at
voltages up to 600V.

SCR Equivalent Circuit of Triac

We shall now see that a Triac is equivalent to two separate SCRs connected in inverse
parallel (i.e. anode of each connected to the cathode of the other) with gates commoned.

Fig. 4.3.2

Fig. 4.3.2 (i) shows the basic structure of a Triac. If we split the basic structure of a Triac
into two halves as shown in Fig. 3.2(ii), it is easy to see that we have two SCRs connected in
inverse parallel. The left half in Fig. 3.2 (ii) consists of a pnpn device (p1n2p2n4) having three
pn junctions and constitutes SCR1. Similarly, the right half in Fig. 3.2(ii) consists of pnpn device
(p2n3p1n1) having three pn junctions and constitutes SCR2.The SCR equivalent circuit of the
Triac is shown in Fig. 3.3.

Suppose the main terminal MT2 is positive and


main terminal MT1 is negative. If the Triac is now fired
into conduction by proper gate current, the Triac will
conduct current following the path (left half) shown in
Fig. 3.2(ii). In relation to Fig. 3.3, the SCR1 is
ON and the SCR2 is OFF. Now suppose that MT2 is
negative and MT1 is positive. With proper gate current,
the Triac will be fired into conduction. The current Fig. 4.3.3

17
Smart Home System

through the devices follows the path (right half) as shown in Fig. 3.2 (ii). In relation to Fig.3.3,
the SCR2 is ON and the SCR1 is OFF. Note that the Triac will conduct current in the appropriate
direction as long as the current through the device is greater than its holding current.

Traic Characteristics

Fig. 4.3.4

Fig. 4.3.4 shows the V-I characteristics of a Triac. Because the Triac essentially consists
of two SCRs of opposite orientation fabricated in the same crystal, its operating characteristics in
the first and third quadrants are the same except for the direction of applied voltage and current
flow.

The following points may be noted from the Triac characteristics:

(i) The V-I characteristics for Triac in the Ist and IIIrd quadrants are essentially identical
to those of an SCR in the Ist quadrant.

(ii) The Triac can be operated with either positive or negative gate control voltage but in
normal operation usually the gate voltage is positive in quadrant I and negative in
quadrant III.

(iii) The supply voltage at which the Triac is turned ON depends upon the gate current.

18
Smart Home System

(iv) The greater the gate current, the smaller the supply voltage at which the Triac is
turned on. This permits to use a Triac to control a.c. power in a load from zero to full
power in a smooth and continuous manner with no loss in the controlling device.

Triac Phase Control Circuit

A Triac can be used to control the average a.c. power to a load by passing a portion of
positive and negative half-cycles of input a.c. This is achieved by changing the conduction angle
through the load. This conduction angle can change by using the Zero crossing Detector.

Zero Crossing Detector is the circuit use to detect the zero occurrences in ac supply.
Based on this zero occurrence we give the 5V high pulse at gate terminal of the Triac. We will
give this pulse depends up on the intensity of appliances (light or fan etc.). If we want more
intensity then we will give the pulse at the time of zero. If we want some intensity we give the
pulse with some delay from the time of zero occurrences. Like this we increase the delay from
the time of zero occurrences to decrease the intensity up to occurrence of next zero.
See the below fig.

Fig. 4.3.5

19
Smart Home System

Here is called firing angle.


C is called conduction angle.

During each positive half-cycle of the a.c., the Triac is off for a certain interval, called
firing angle (measured in degrees) and then it is triggered on and conducts current through the
load for the remaining portion of the positive half-cycle, called the conduction angle C.
At the firing angle we will give the high pulse to the Triac and it start the conduction until the
next zero occurring. If we are increasing the delay time means we are increasing the firing angle
and decreasing the conduction angle C. As a result, smaller a.c. power is fed to the load.
During each negative half-cycle of the a.c., a similar action occurs except that now current in the
load is in the opposite direction.

Fig. 4.3.5 shows the waveforms of the line voltage and gate voltage. Only the shaded
portion of the positive and negative half-cycles passes through the load. We can change the
phase angle of gate voltage by changing the delay time i.e. firing angle and conduction angle
C. Thus a Triac can control the a.c. power fed to a load. This control of a.c. power is useful in
many applications such as industrial heating, lighting etc.

Zero Crossing Detector

Zero Crossing Detector is the circuit used to detect the zero voltage occurrences in the
AC supply. See the below fig. 4.4.1

Fig. 4.4.2

20
Smart Home System

This Zero crossing detector has mainly a Bridge Rectifier and a Transistor. Here the
bridge rectifier used to convert the AC supply to full wave. So that the output voltage has the all
positive cycles.

This circuit has a transistor, a 10kohm resistor connected at the collector terminal of the
transistor, emitter terminal connected to the ground and VCC is 5V. The output wave form of the
bridge rectifier applied at the gate terminal. This Transistor has the base to emitter voltage 0.7v
so that the transistor turns on at above the 0.7v of the gate voltage and turn off at below the 0.7v
of the gate voltage. Due to the turn on of this transistor it get short then we get 0V at the collector
terminal. If the transistor is turn off then it get open and we get the output voltage 5v up to the
transistor turn on. So we get the 5V pulse from the 0.7v to 0.7v.This pulse is used as input to find
the zero crossing.

4.2. Software Development


In software development of our project SHS, there are two type of clients and the
microcontroller is working as server here. These complete these thing can be programmed in
there different languages.

Microcontroller - C++

Smart Phone - Android

Laptop Application - Java

For these developments, Context, Use Case and Sequence Diagrams are presented below.

21
Smart Home System

4.2.1. Android Application

4.2.1.1. Class Diagram

Fig 4.2.1.1 Class Diagram

4.2.1.2. Use Case Diagram

Fig 4.2.1.2 Use Case Diagram

22
Smart Home System

4.2.1.3. Sequence Diagram

Fig 4.2.1.3 Sequential Diagram

23
Smart Home System

4.2.2. Java Application

4.2.2.1. Context Diagram

4.2.2.1. Context Diagram

4.2.2.2. Class Diagram

Fig 4.2.2.2 Class Diagram

24
Smart Home System

4.2.2.3. Sequential Diagram

Designing of Request and Response

In Smart Home System, we are using C++ programming in microcontroller and for client
application development, java and android is being used. For communication purpose, these
client program must send request to the micro controller and it receives the request, process it,
performs the corresponding action and then it sends response.

25
Smart Home System

These are the some of the request and their corresponding response given below.

Request and Response Pattern:


REQ : ReqId : ReqType : ReqAction : ( ReqParameters )

RES : ReqId : ReqType : ReqAction : ( ResponseType, Response )

And the ReqType is having four different values.

000 Universal related requests

001 House related requests

002 Room related requests

003 Switch related requests

Examples Codes:

REQ TYPE REQ ACTION REQUEST AND RESPONSE


000 Universal 000 - Login REQ:000:000:000:(universal, password)
RES:000:000:000:(1,1)
001 Logout REQ:000:000:001:()
RES:000:000:001:(?)
002 - Version REQ:000:000:002:()
RES:000:000:002:(1,Vno)
001 House 001 no of Rooms REQ:000:001:001:()
RES:000:001:001:(1,noRooms)
002 Block 001 no of Switches REQ:002:002:001:(B_Id)
RES:002:002:001:(B_Id,lable,noSwitches)
003 Switch 001 get Sw Details REQ:002:003:001:(sid)
RES:002:003:001:(1,sid,stype,active,status,slable)
002 change Sw Status REQ:035:003:002:(sid,status)
RES:035;003:002:(1,1)

26
Smart Home System

Chapter 5
CODING

27
Smart Home System

Below are the main codes that transmit the request and response from microcontroller to client and
vice versa.

Java Application Serial Communication Code

class SerialTest implements SerialPortEventListener{

/** Handles all kind of serial port activities */

private static SerialTest serialObj; // obj to send data

// isInitiated = true - means its ready to transfer data

public static boolean isInitiated = false;

SerialPort serialPort;

// The port, normally used

private static final String PORT_NAMES[] = {

"/dev/tty.usbserial-A9007UX1", // Mac OS X

"/dev/ttyACM0", // Raspberry Pi

"/dev/ttyUSB0", // Linux

"COM8", // Windows

};

private BufferedReader input;

private PrintStream output;

/** Milliseconds to block while waiting for port open */

private static final int TIME_OUT = 2000;

/** Default bits per second for COM port. */

private static final int DATA_RATE = 9600;

SerialTest(){

this.initialize();

28
Smart Home System

public void initialize() {

// the next line is for Raspberry Pi and

// gets us into the while loop and was suggested here

// was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186

// System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

CommPortIdentifier portId = null;

Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

//First, Finds an instance of serial port as set in PORT_NAMES.

while (portEnum.hasMoreElements()) {

CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();

for (String portName : PORT_NAMES) {

if (currPortId.getName().equals(portName)) {

portId = currPortId;

isInitiated = true;

break;

if (portId == null) {

System.out.println("Could not find COM port..");

isInitiated = false;

return;

29
Smart Home System

try {

// open serial port, and use class name for the appName.

serialPort = (SerialPort) portId.open(this.getClass().getName(),

TIME_OUT);

// set port parameters

serialPort.setSerialPortParams(DATA_RATE,

SerialPort.DATABITS_8,

SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);

// open the streams

input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

output = new PrintStream(serialPort.getOutputStream());

// add event listeners

serialPort.addEventListener(this);

serialPort.notifyOnDataAvailable(true);

} catch (Exception e) {

System.err.println(e.toString());

public synchronized void close() {

// This should be called when you stop using the port.

// This will prevent port locking on platforms like Linux.

if (serialPort != null) {

serialPort.removeEventListener();

serialPort.close();

30
Smart Home System

public void sendData(String msg){

/** Sends given data to Serial port */

System.out.println(msg);

output.println(msg);

// Handle an event on the serial port. Read the data and print it.

@Override

public synchronized void serialEvent(SerialPortEvent oEvent) {

if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {

try {

String inputLine=input.readLine();

if(inputLine.startsWith("RES:")){

System.out.println(inputLine);

reqHandler.setResponse(inputLine);

else{

System.out.println(inputLine);

} catch (Exception e) {}

// Ignore all the other eventTypes, but you should consider the other ones.

public static SerialTest getSerialObj(){

31
Smart Home System

/** Returns Serial Object */

if(!isInitiated){

serialObj = new SerialTest();

if(isInitiated)

return serialObj;

else

return null;

Java Application - Request Handler Class

class reqHandler{

/** handles and stores all kinds of requests & their responses */

// keeps all object of this class

private static final Map<Integer, reqHandler> store = new HashMap<>();

private static int id = 0;

int reqId = 0;

private String req = "";

String response = "";

private boolean isRes = false;

SerialTest obj = SerialTest.getSerialObj();

reqHandler(){}

public static int sendRequest(String req){

// sends requests

32
Smart Home System

reqHandler r = new reqHandler();

r.reqId = id;

r.req = req;

r.isRes = false;

r.sendReq();

store.put(r.reqId, r);

id++;

return r.reqId;

void sendReq(){

/** Sends the req through serial port */

obj.sendData("REQ:" + this.reqId + ":" + this.req);

static String getResponse(int rId){

/** returns corresponding response of rId */

reqHandler r = store.get(rId);

// waits until the response is set

while(!r.isRes){

try{

Thread.sleep(100);}

catch(InterruptedException ie){}

return r.response;

static void setResponse(String msg){

33
Smart Home System

// msg format : RES:0:0:0:(1,1)

// getting source for msg

String[] arr = msg.split(":");

int rId = Integer.parseInt(arr[1]);

reqHandler r = store.get(rId);

// trimming response from brakets

String response = arr[4];

StringBuilder s = new StringBuilder();

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

if(i == 0 || i == response.length()-1) continue;

s.append(response.charAt(i));

response = s.toString();

r.response = response;

r.isRes = true;

Android Application Request Sending Code


package in.rgukt.shs.core;

public class Request {

private int reqId, reqType, reqAction;

private String reqParams;

public Request(int reqId, int reqType, int reqAction, String reqParams) {

this.reqId = reqId;

this.reqType = reqType;

34
Smart Home System

this.reqAction = reqAction;

this.reqParams = reqParams;

public void setReqId(int reqId) {

this.reqId = reqId;

public void setReqAction(int reqAction) {

this.reqAction = reqAction;

public void setReqType(int reqType) {

this.reqType = reqType;

public void setReqParams(String reqParams) {

this.reqParams = reqParams;

public int getId() {

return reqId;

@Override

public String toString() {

return "REQ:" + reqId + ":" + reqType + ":" + reqAction + ":"

+ reqParams;

35
Smart Home System

Android Application Response Getting Code

package in.rgukt.shs.core;

import android.content.Context;

import android.widget.Toast;

public class Response {

private String response;

private int resId, resType, resAction;

private String resParams;

private String[] params;

public Response(String response) {

this.response = response;

String[] array = response.split(":");

resId = Integer.parseInt(array[1]);

resType = Integer.parseInt(array[2]);

resAction = Integer.parseInt(array[3]);

resParams = array[4];

params = resParams.substring(1, resParams.length() - 1).split(",");

public int getResId() {

return resId;

public int getResType() {

return resType;

public int getResAction() {

36
Smart Home System

return resAction;

public String getResParams() {

return resParams;

public int getParamAsInt(int index) {

return Integer.parseInt(params[index]);

public String getParamAsString(int index) {

return params[index];

public boolean isSuccessful(Context context, int requestId) {

if (getParamAsInt(0) == 0 || requestId != getResId()) {

Toast.makeText(context, "Error occured in Processing Request!",

Toast.LENGTH_LONG).show();

return false;

return true;

Microcontroller Code for Getting Request

Block SHS::bCon[] = {

Block(0,"T-61"),

37
Smart Home System

};

Switch SHS::sCon[] = {

Switch(1,'1',12,"Light-1","Tube Light In Area - 1"),

Switch(2,'1',11,"Light-2","Tube Light In Area - 1"),

};

String data = "";

requestHandler r;

void setup(){

// Initializing Serial Communication

Serial.begin(9600);

Serial.println("SHS Initializing..");

// Initializing Switches

SHS s;

s.initializePinModes();

void loop(){

// Reading data from USB - Serial Communication

if(Serial.available() > 0){

char c = Serial.read();

if(c == '\n'){

r.processRequest(data);

data = "";

else data += c;

38
Smart Home System

Microcontroller Code for Switch Class


class Switch{

public:

static int sNo;

int sId;

char sType;

bool active;

int sPin;

char sStatus;

String sLabel;

String sDesc;

Switch(int id, char type, int pin, String lbl, String desc);

};

int Switch::sNo;

Switch::Switch(int id, char type, int pin, String lbl, String desc){

sId = id;

sType = type;

active = true;

sPin = pin;

sStatus = '0';

sLabel = lbl;

sDesc = desc;

sNo++;

39
Smart Home System

Microcontroller code for Block Class

class Block{

public:

static int bNo;

int bId;

String bLabel;

int sNo;

Block(int id, String lbl);

};

int Block::bNo;

Block::Block(int id, String lbl){

bId = id;

bLabel = lbl;

bNo++;

sNo = 0;

Microcontroller Code for SHS Class

class SHS{

public:

static Block bCon[];

static Switch sCon[];

static int getTotalBlocks();

40
Smart Home System

static int getTotalSwitches();

void initializePinModes();

static String getBDetails(int bid);

static int findIndex(int sid);

static String getSDetails(int sid);

static int changeSStatus(int sid, char stat);

static String getSDesc(int sid);

static String getSStatus(int sid);

static void lockSwitch(int sid);

static void unlockSwitch(int sid);

};

41
Smart Home System

Chapter 6
OUTPUT

42
Smart Home System

Java GUI Application Connect to Hardware and Login pages

43
Smart Home System

Java GUI Application getting Details and Show Switches pages

44
Smart Home System

Java GUI Application Switching On or Off

45
Smart Home System

Java GUI Application WIFI LOG

46
Smart Home System

Android Application GUI

47
Smart Home System

Chapter 7
CONCLUSION

48
Smart Home System

Conclusion

Smart home system - the name itself representing the meaning that the home is very smart. Smart
means it as to sense the environment, persons, and their works, etc. With these inputs, it has to process
the information and then it has to respond by performing actions. So, the system should be having all
kinds of sensors for getting inputs and performing outputs such as switching on or off the bulbs or fans,
and finally it has to process the input then perform output. This is in general nothing but thinking. So,
completely the Smart Home System is having three levels.

1) Capability to perform outputs.


2) Capability to sense
3) Capability to process

So, as a final year students we have taken this project to analyze and learn the most basic level of
hardware programming as a part of making a value to our final year project. Now we are happy to say
that we have successfully completed the first level of Smart Home System and also capable of
understanding any kind of home automation system. And we will also implement those two levels of
SHS soon.

Future Enhancement

As we have told you that we have completed the first level of SHS. And two more levels
are pending, which involves the sensors integrating and programming the microcontroller to
think. Integrating sensors means the system has to sense all kind of changes in the
environment. Here we have to deal with advanced hardware concepts and programming the
microcontroller to think. Means, we have to deal with programming like Digital Image
Processing, Artificial Intelligence and computer vision etc. we are hoping to archive these.

And any future enhancement to any system that system should have properly designed
by following standards. This provides the probability to upgrade the total system.

49
Smart Home System

Chapter #
BIBLIOGRAPHY

50
Smart Home System

For Hardware

Google
www.arduino.cc
www.stackoverflow.com
www.elechouse.com
www.electronicstutorials.com
www.daycounter.com
www.electronicscourse.com
electronics.stackexchange.com
www.wikibooks.org Serial Programming
Book Simple Methods for Detecting zero crossing
Book UART WIFI Concepts
Book C++, The Complete Reference(3ed edition)

For Software

Google
www.stackoverflow.com Problem Solving
www.tutorialspoint.com Advanced Android Tutorial
Book Java, The Complete Reference (7th edition)
Book Advanced Android Learning

51

You might also like