Vous êtes sur la page 1sur 135

PSZ 19:16 (Pind.

1/07)

UNIVERSITI TEKNOLOGI MALAYSIA


DECLARATION OF THESIS / UNDERGRADUATE PROJECT REPORT AND COPYRIGHT
Authors full name : HAFIZUL SHAZWANN BIN MOHAMAD
Date of Birth

: 01ST MARCH 1991

Title

: SMARTHOME WIRELESS POWER MONITORING SYSTEM

Academic Session : 2013/2014


I declare that this thesis is classified as:

CONFIDENTIAL

(Contains confidential information under the Official Secret Act


1972)*

RESTRICTED

(Contains restricted information as


organization where research was done)*

OPEN ACCESS

I agree that my thesis to be published as online open access


(full text)

specified

by

the

I acknowledged that Universiti Teknologi Malaysia reserves the right as follows:


1. The thesis is the property of Universiti Teknologi Malaysia
2. The Library of Universiti Teknologi Malaysia has the right to make copies for the
purpose of research only.
3. The Library has the right to make copies of the thesis for academic exchange.
Certified by:

SIGNATURE
910301-08-6331
(NEW IC NO/PASSPORT)
Date:

NOTES:

20 JULY 2014

SIGNATURE OF SUPERVISOR
DR. KAMALUDIN MOHD YUSOF
NAME OF SUPERVISOR
Date:

20 JULY 2014

If the thesis is CONFIDENTAL or RESTRICTED, please attach with the letter from
the organization with period and reasons for confidentiality or restriction.

I hereby declare that I have read this thesis and in my opinion this thesis is
sufficient in terms of scope and quality for the award of the degree of Bachelor of
Engineering (Electrical Medical Electronics)

Signature

: .........

Name of Supervisor

: Dr. Kamaludin Mohd Yusof

Date

20 JULY 2014

SMARTHOME WIRELESS POWER MONITORING SYSTEM

HAFIZUL SHAZWANN MOHAMAD

A report submitted in partial fulfilment of the


requirements for the award of the award of the degree of Bachelor of Engineering
(Electrical Medical Electronics)

Faculty of Electrical Engineering Universiti Teknologi Malaysia

JUNE 2014

ii

I declare that this thesis entitled SmartHome Wireless Power Monitoring system is
the result of my own research except as cited in the references. The thesis has not
been accepted for any degree and is not concurrently submitted in candidature of any
other degree.

Signature

....................................................

Name

HAFIZUL SHAZWANN BIN MOHAMAD

Date

20 June 2014

iii

To my beloved mother and father who always there for me Hasliza binti Mat Hashim
and Mohamad bin Tomin

To my siblings Hafizul syazlami bin Mohamad, Hafizul Shafiq bin


Mohamad,Hafizul Ikhwann bin MOhamd.

To my lecturer and supervisor, for their guidance and encouragement Dr.


Kamaludin Mohd Yusof.

To my friends, for their unconditionally support

iv

ACKNOWLEDGEMENT

In the Name of ALLAH, the Most Gracious and the Most Merciful Praise be
to ALLAH,

Firstly, I would like to thank Allah S.W.T. for giving me strength and good
health to complete this undergraduate study here in UTM. Then, I would like to
express my deepest gratitude to my supervisor, Dr Kamaludin Mohd Yusof, who had
continuously giving me support, ideas, guidance for the project. It would be difficult
to complete the course without his support and understanding.

In particular, I wish to express my sincere appreciation to my friends,


`AbduRahman Suratman, Muhammad Ridwan, Helmi Ali, Zaki (Pak Yob), Hisham
Roslan, Anwar Zharif, Zhahran Che Hassan, Harrith (Lah), Dalimi,Amir, and Taufiq
Hidayat. They have contributed towards my understanding and thoughts.

My sincere appreciation extends to all my undergraduate friends especially


SEP member of batch 2010-2014 who have helped and shared brilliant ideas
throughout the whole year.

Lastly, for those who giving me support indirectly or directly, many thanks to
all of you and may Allah bless you for the good deed you have done, InshaAllah...

ABSTRACT

The increasing of electric tariff in Malaysia are affecting the financial of the
industrial and domestic users. The additional cost make the users need to absorb its
in the production cost and daily living expenses. For domestic users, this will change
their style of living. The users need to use the electricity with effectively without any
waste. According to this problem, the users try to save their electricity consumption
by switch off the electrical appliance when is not been used. However, this method is
not efficient because the user only concern about the electric consumption after they
get the electricity bill. Hence, in this project we are going to develop a smart home
wireless power monitoring system, which is the system will show the value of the
electric consumption in power (Watt) and also in ringgit Malaysia according to the
Tenaga Nasional Berhad (TNB) tariff. This system is included with the internet
connection where the user be able to monitor the electric consumption anywhere via
their smartphone or computer. The design of this system involves a hardware and
software development. In the hardware design, the current sensor will measure the
current value in each miniature circuit breaker (MCB) in the DB board and send the
current value to the raspberry-PI through wireless module. The raspberry-PI will
save the value in database. While in the software design, a web browser has been
developed as a user interface, where the user will be able to monitor the electric
consumed in power and in ringgit Malaysia. By showing the electric consumption in
ringgit Malaysia is the best way to aware the user about the electric consumption at
home for every hour, daily, weekly or monthly.

vi

ABSTRAK

Peningkatan tarif elektrik di Malaysia memberi kesan kepada kewangan


pengguna industri dan domestik. Kos tambahan membuat pengguna perlu menyerap
dalam kos pengeluaran dan perbelanjaan kehidupan harian. Bagi pengguna domestik,
keadaan ini akan mengubah gaya hidup mereka. Para pengguna perlu menggunakan
elektrik dengan berkesan tanpa ada apa-apa pembaziran. Menurut masalah ini,
pengguna cuba untuk menjimatkan penggunaan elektrik mereka dengan menutup
suis dari perkakas elektrik apabila tidak digunakan. Walau bagaimanapun, kaedah ini
tidak berkesan kerana kebimbangan pengguna hanya timbul selepas mengetahui
jumlah penggunaan elektrik selepas mereka mendapat bil elektrik. Oleh itu, dalam
projek ini kami akan merekacipta satu sistem wayarles pemantauan kuasa pintar,
yang merupakan sistem yang akan menunjukkan jumlah penggunaan elektrik (Watt)
dan juga dalam ringgit Malaysia mengikut tariff daripada Tenaga Nasional Berhad
(TNB). Sistem ini adalah termasuk dengan sambungan internet di mana pengguna
dapat memantau penggunaan elektrik di mana-mana sahaja melalui telefon pintar
atau computer riba mereka. Reka bentuk sistem ini melibatkan rekacipta perkakasan
dan perisian. Dalam reka bentuk perkakasan, elektrik sensor akan mengukur nilai
semasa dalam setiap pemutus litar kecil (MCB) pada papan DB di rumah dan
menghantar nilai semasa kepada raspberi-PI melalui modul wayarles. Selepas itu,
raspberry-PI akan menyimpan nilai atau jumlah penggunaan kuasa ke dalam
pangkalan data. Manakala dalam reka bentuk perisian, pelayar web telah direkacipta
sebagai antara muka pengguna, di mana pengguna dapat memantau jumlah
penggunaan elektrik yang digunakan di dalam kuasa dan ringgit Malaysia. Dengan
menunjukkan penggunaan elektrik dalam ringgit Malaysia adalah cara terbaik untuk
menyedarkan pengguna tentang penggunaan elektrik di rumah untuk setiap jam,
harian

,mingguan

atau

bulanan

vii

TABLE OF CONTENTS

CHAPTER

TITLE

DECLARATION

ii

DEDICATION

iii

ACKNOWLEDGEMENT

iv

ABSTRACT

ABSTRAK

vi

TABLE OF CONTENTS

vii

LIST OF TABLES

xi

LIST OF FIGURES

xii

LIST OF ABBREVIATION

xiv

LIST OF APPENDICES

PAGE

INTRODUCTION
1.1

Introduction

1.2

Problem Statement

1.3

Research Objectives

1.4

Scope of Project

1.5

Achievment

1.6

Thesis Organization

1.7

Methodology

LITERATURE REVIEW
2.1

Introduction

2.2

Previous Related Works

viii
2.3

Element in smart home system

10

2.4

Characteristics of Wireless Sensor Network.

11

2.5

Networking System

11

2.5.1

11

2.6

2.7

The Router

System Implementation

13

2.6.1

Hardware Platform system

14

2.6.2

Sensor Nodes

16

2.6.2.1

ZigBee

16

2.6.2.2

nRF24L01 Single Chip 2.4GHz Transceiver

18

2.6.2.3

Bluetooth

21

2.6.3

Home Platform

22

2.6.4

User Intefaces

25

Summary

26

METHODOLOGY
3.1

Introduction

28

3.2

System Specification and Requirement

29

3.2.1 Hardware Specification

30

3.2.2

31

3.3

Software Specification

System Design

33

3.3.1

Home Network

36

3.3.2

Configuring a Single Set Computer Raspberry Pi as a access


point (AP)
38

3.3.3

Developing the database and smart home web page for user
interface.
41

3.4

Summary

43

RESULTS
4.1

Introduction

44

4.2

Setup current sensor ACS712

45

ix
4.3

Setup the raspberry Pi as access point (AP)

48

4.3

Result Communication between smart home power monitor and Access


Point (AP)
50

4.4

Result Communication between Access Point and database

4.5

Result Communication between Access Point and smart home web

4.6

51

page

54

Summary

56

DISCUSSION
5.1

Introduction

57

5.2

Getting accurate reading of the current sensor

57

5.3

Create wireless protocol transmits and receives between the Smart


Home power monitoring device and access point (AP)

62

5.4

Insert the receive data into the database

62

5.5

Summary

63

CONCLUSION
6.1

Introduction

64

6.2

Conclusion

64

6.3

Limitation and Recommendation for Future Works

65

PROJECT MANAGEMENT
7.1

Introduction

66

7.2

Project Schedule

66

7.3

Cost Estimation

69

REFERENCES

72

APPENDICEIES
APPENDIX A

74

APPENDIX B

91

x
APPENDIX C

101

xi

LIST OF TABLES

TABLE NO.

TITLE

PAGE

2.1

Summary of Smart Home system element

2.2

Wireless module capability

10

2.3

nRF24L01 module capability

19

2.4

Data format of the nRF24L01 chip

21

2.5

Compare transmission rate of the multi-chip system

21

2.6

Discription about Model A and Model B of raspberry Pi

24

3.1

Hardware specification for the Smart Home Wireless 30


Power Monitoring system

3.2

Software specifications information

31

3.3

Advantages using MySQL

32

7.1

Project Gantt Chart (Semester One)

68

7.2

Project Gantt Chart (Semester Two)

69

7.3

Hardware cost estimation

70

7.4

Electronic component cost estimation

71

xii

LIST OF FIGURES

FIGURE NO.

TITLE

PAGE

1.1

Flowchart of methodology

2.1

Mesh network topology

12

2.2

System Implementation of the SmartHome

14

2.3

Structure Decomposition Of The Power Outlet Module

15

2.4

Structured design inside of the PPCOM hardware

15

2.5

Structured design outside of the PPCOM hardware

15

2.6

The model of ZigBee wireless network

16

2.7

XBee RF Module and XBee Wi-Fi RF Module

18

2.8

Structure of the hardware platform

22

2.9

A Single set computer Raspberry Pi

23

2.10

Dsecription of Raspberry Pi

23

2.11

Application Programming Interface (API) of Smart 25


Phones and web browser.

2.12

Stationary Monitoring Device

26

2.13

Mobile Device- UbiLense

26

3.1

Project flow of system design

28

3.2

System Architecture Of Smart Home Wireless Power 30


Monitoring System device

3.3

The Smart Home Wireless Power Monitoring System 33


Design

3.4

Flow chart system design

34

3.5

Flow chart of Home Network

36

3.6

Win32 Disk Imager software windows interface

37

3.7

Terminal software Linux interface

38

3.8

XAMPP software windows interface

41

xiii
3.9

Flowchart of the database and SmartHome web page

42

4.1

Full Setup of Smart Home Wireless Power Monitoring 44


System

4.2

Current sensor ACS712 and arduino

44

4.3

Analog read serial command to reads an analog input 45


from current sensor

4.4

Smart Home Wireless Power monitoring system

46

4.5

Wiring of the smart home power monitoring device with 47


main circuit breaker (MCB)

4.6

A single set computer Raspberry Pi

47

4.7

The connection between the Raspberry Pi and the 48


nRF24l01 module

4.8

Smart home wireless power monitoring system prototype 49


and AP

4.9

Data received from smart home power monitoring

50

4.10

Database of the smart home system

53

4.11

Smart Home WEB page login system

53

4.12

Smart Home GUI interface

54

4.13

Power consumption graph

54

4.14

Value power consume in ringgit Malaysia

55

5.1

Experiment result measured the current

57

5.2

Current sensor value when no load

58

5.3

Experiment procedure

59

5.4

Current sensor reading with load

59

5.5

Step to read the current sensor

60

5.6

Command to convert the float type to the character.

62

xiv

LIST OF ABBREVIATION

API

Application Programming Interface

AP

Access Point

FIFO

First Input First Output

FTP

File Transfer Protocol

GPIO

General Purpose Input/Otput

ISM

Industrial Scientific and Medical

IEEE

Institute of Electrical and Electronics Engineers

MCB

Main Circuit Breaker

MCU

Multipoint Control Unit

OSI

Open System Interconnection

OS

Operating System

PLC

Programmable Logic Control

PSRR

Power Supply Rejection Ratio

RF

Radio Frequency

RAM

Random Access Memory

SPI

Serial Peripheral Interface

TNB

Tenaga Nasional Berhad

USB

Universal Serial Bus

LIST OF APPENDICES

APPENDIX

TITLE

PAGE

SmartHome Power Monitoring device soft code

73

Raspberry Pi (AP) soft code

90

Setting up a Web server using Raspian Wheezy on


the Raspberry Pi

100

CHAPTER 1

INTRODUCTION

1.1

Introduction

Nowadays, much research have been carried out to improve the Smart Home
system. From the previous research various methods had been introduced to improve
the Smart Home system and one of the important ways to improve the smart home
system is to change from wired transmission to the wireless communication because
the major weakness of the wired connection is the limitation of network ranges and
upgrading difficulty. On those consequences, researchers have come to the idea of
doing it wirelessly.

Hence,

with

the

rapid

development

of

wireless

communications,

microelectronic technology, integrated circuit and sensing technology, the wireless


sensor network (WSN) has achieved a great progressed, which is now most of the
WSNs node had combine sensing, computation and communication into a single
device [1], so to use wireless communication is not impossible anymore.

Wireless communication reduces the hassle of making a new connection and


will increase the network range. In wireless, the Smart Home network range can be
extended with the implementation of wireless sensor network through multi-hopping
technique or so called ad-hoc network. In multi-hopping technique, the signal from
the source to destination is sent through fewer wireless hops. In Smart Home system,
a special device is needed to control the Smart Home.

2
In this thesis we focuse on the wireless power monitoring system where the
development of a hardware device and software application that can be used by the
users to monitor their power usage at home. The working principle of Smart Home
Wireless Power Monitoring system is by connecting the current sensor at each of the
main circuit breaker (MCB) in the distribution board at home. Then the current
sensor will measure each of the MCB power consumed and send the current sensor
data to the access point (AP). In this Smart Home system, we set the raspberry Pi as
an AP. This AP will receive the current sensor data and save the current sensor data
into the database.

The user can easily monitor their power consumption by connecting to the
internet using computer or Smartphone and directly can monitor their power usage
by login into the Smart Home web pages. The user also can analyze the data by see
the graph at web page that automatically update for every 10 seconds. The web page
will refersh automatically after 10 second. It will make the system convenience to the
user to monitor their power consumption at anywhere as long as they have internet
connection. With the aid of web page the user can see the performance of the power
consumption every hour, daily, weekly or monthly and it depend on user when to
monitor their power consumed. Furthermore, the user also can directly see their
power consumption in ringgit Malaysia and it rate follows the current TNB tariff.

1.2

Problem Statement

The greenhouse effect is important to us to warm enough the earth for human
to live. But if the greenhouse effect is too high, it could make the earth warmer than
usual and even a little warming of the earth it may cause problems for humans, plant
and animal. This warming is what we call global warming and it cause by the
greenhouse effect. Global warming is a mainly attributed to carbon dioxide (CO2)
emissions that cause the greenhouse effect to be worse. One of the contributor to the
emission of the carbon dioxide is arise from generation of the electricity from fossil
fuels. From the report of the electricity supply industry in Malaysia performance and
statistical information 2011, show that the statistic maximum demand of electricity

3
had increase by 2.7 % from 15072 MW in 2010 to 15476MW in 2011 [2]. From this
statistic report TNB needs to increase the electric supply to support the demand of
electricity in Malaysia which is more fossil fuel will be used to generate electricity
and indirectly will contributed to the emission of carbon dioxide at the atmosphere.

One way to reduce emission of carbon dioxide (CO2) is therefore to reduce


the overall consumption of electricity in industry and the private sector. Home
owners, of course themselves have a high interest in reducing energy consumption
because it is a important cost factor. Here usage awareness alone has the potential to
reduce consumption by 15 % in private households [3]. However, standard electricity
meters that are widely deployed in homes today, and the suppliers` analog billing
system based on monthly accounting periods, lack the feedback capabilities that are
necessary to increase energy awareness and positively affect customers` behaviour
[3]. Therefore, this project has purpose to alerting the user by providing the power
monitoring and controlling home appliance interface and measure the total power
usage in Malaysia tariff, rather than see the total power in kilowatt per hour that is
not aware the user. Within this SmartHome system the user can improve the pattern
in power consumption of energy consumers thus reducing the financial burden of
electricity companies [4].

1.3

Research Objectives

The main objective of this project is to develop a Smart Home wireless power
monitoring system by using WSN, single set small computer Raspberry Pi and
Android app. The system enables the user to monitoring their electricity power
consume at home and enable to control their home appliance on/off switch via
internet connection.

4
The wireless sensor network (WSN) will use nRF24L01 module as a wireless
communication to transfer packet data to the router which is raspberry Pi. The
database on a Raspberry Pi also will be synchronized with cloud storage server. This
are several objectives to be achieved ;

i.

To develop a power monitoring system that can measure power


consumption.

ii.

To analysis and monitor the power usage of different home


appliances.

iii.

To determine the total power consumption and measured the total cost
using TNB tariff.

iv.

To give the direct feedback to the customer about their power usage
and increase the energy awareness by showing the value in TNB
tariff.

1.4

Scope of Project

In the effort of achieving the objectives, several scopes have been outlined.
The development of the project is estimated to involve 70% of hardware and 30% of
software. The scopes of the project involve:

i.

Developing a power monitoring hardware that can measure the power


consumption of the home appliance.

ii.

Developing a communication between wireless sensor nodes and the web


server.

iii.

Developing end to end communication between client and the we server


using a wireless local area network.

iv.

Developing a synchronization database between web servers and cloud


storage that enable the user to access the data on long distance or remote
communication.

5
1.5

Achievment

This project was presented on 20th May 2014 during the Telecomunication
Exhibition Day (TED). TED have divided the competition in six category which are;
session A: Antenna, RF & Microwave, session B: Optical & Photonics, session C:
Communication System, session D: Wireless Communication & Acoustic, session E:
Next Generation Network & Multimedia Application, and session F: Sensors. My
project was belong in session D where the panel consist from academic panels and
industrial panels. Dr. Nik Noordini Nik Abdul Malik (Head of Session) and Ir. Dr.
Mokhtar Harun are academic panels. While Ir. Mohd Hanif Yassin (TM) and Mr.
Amiruddeen Wahid (Measat) are industrial panel. During this exhibition day we are
giving two task where for the first task we need to present our project using power
point slide. We are given ten minutes to present our project and after that, 15 minutes
to do a demonstration to prove that our project was succesfully work. At the end of
the exhibition day my project was announce as a first runner up from seven
candidates in that session. For the first runner up, we received certificate and silver
medal. During demonstration session, the industrial panel and suggested that my
project has potential to be commercialize in the industrial and we also has been
adviced from Ir. Dr. Mokhtar Harun to implement this project to the factory because
the factory needs the power monitoring system to monitor their power consumption.

1.6

Thesis Organization

This thesis contain of seven chapters. The first chapters give general overview of the
entire project and discuss about the background of the Smart Home Wireless Power
Monitoring system, problem statement; objectives and scope of the project.

The second chapter will discuss on the literature review of the previous
project and the method approach to send the data wirelessly that relate to the topic.

6
In chapter three, the methodology and procedures implemented in the project
is discussed clearly. The methodology and approach of this project have been divided
into three phases. 1st phase is to determine the concept and requirement to design the
system. In this 1st phase also include the system specification of the hardware and
software. 2nd phase is to design the architecture of the Smart Home system. Then
the 3rd level is to implement the design of the system. Finally the 4th phase has
verified the validity of the design via testing to ensure the system meets the required
specification. Chapter four will show and demonstrate the result of this project.
Discussion and conclusion will covered in chapter 5 and chapter 6. In chapter 6 also
include the project with project achieve and limitations, and recommendations for the
systems future directions. The last chapter which is chapter seven, it discussed about
the project management. In this chapter include project schedule and cost estimation.

1.7

Methodology

The first step for this final year project is getting the project title and
objectives. Discussion with the supervisor was made to find the most suitable title for
this project. The selection of suitable project title is necessary because the project
title will give the first impression on the project to be developing as a whole.

After the suitable project title was chosen, the next step is conducting
literature review before writing the project proposal. All the information needed to
complete this project is gathered and studied by reviewing journals, articles, books
and previous research that related to this project. The project proposal was later
prepared before beginning the project.

Both hardware and software research is done to improve the understanding in


order to complete the project efficiently. The functions of each component, tools and
instruments needed to be used in this project will be studied to reduce the time
needed for the designing process. Software research will be done to increase the
understanding and avoid many mistakes during the programming process.

7
The implementation of hardware and software will be done separately. After
all of the components needed for this project is purchased, the project development
will preceded by installing the hardware according to the designed system. Then, the
software will be programmed to provide the Graphical User Interface (GUI) for this
project. After both hardware and software implementation is done, the next step is to
do system integration between the hardware and the software. The system will be
tested and if there is any error, troubleshoot process will be done to find the cause of
the problem.

The important procedure before documentation process of this project can be


done is data collection. Data must be collected to ensure that the system is working
properly as planned before.

Figure 1.1: Flowchart of methodology

CHAPTER 2

LITERATURE REVIEW

2.1

Introduction

Literature review was carried out throughout the previous project to gain
information and skills needed to complete this project. The main sources for this
project are previous related projects, research thesis, books, journals and articles
which are mostly obtained from online database provided by UTM. This chapter
highlights the basic concept and all the fundamental theories which related to this
project

2.2

Previous Related Works

Several studies on previous related projects have been carried out before the
project development is made. Previous projects are useful as references which help
this project to succeed with less trouble.

10
2.3

Element in smart home system

Smart Home system is the management and control of incorporated of many


small system at home. Smart Home system can be monitor system and control
system. For example lamp switch, temperature monitoring, motion detection, power
monitoring, home surveillance and other sensors [5]. Sensors in these system can be
controlled using an interface device such as a remote control, computer and
Smartphone. With the increasing variety of sensors to be controlled and monitored,
the primary system should be more specific to the built-in sub-systems to be Smart
Home system. This range of systems can be wired or wireless depending on the
application and purpose of the Table 2.1 show the summary of Smart Home system
elements.

Table 2.1: Summary of Smart Home system element

Element in Smart Home system


Sensor

Example
Temperature monitoring, lamp switch,
home surveillance, power monitoring

User interface devices

Remote control, computer, laptop,


Smartphone, tablet

Application interfaces

Android , iOS , web browser

Types of networking

Wired-fiber optic, coaxial cable


Wireless-Bluetooth, Wi-Fi, RF, Zigbee

Centralizing control

Micro controller, PLC, computer ,


raspbbery-PI

11
2.4

Characteristics of Wireless Sensor Network.

The main characteristic of wireless sensor network is the ability to transmitrs


the data to the other nodes and receives the data from the other nodes. Wireless
communication is used to transfer information between two or more points that are
not connected by an electrical conductor [1]. With the rapid development of wireless
communications, microelectronic technology, integrated circuit and sensing
technology, the WSN have achieved great process which is WSNs had combine the
sensing, computation and communication into a single tiny device [5]. Table 2.2
show the wireless module capability which are Bluetooth, Wi-Fi, and zigbee [6].

Table 2.2: Wireless module capability


Standard

Range

Number of

Frequency

Data

node

band

protection

Power use

Bluetooth

10m

2.4GHz

16 bit CRC

High

Wi-Fi

100m

32

3.1-10.6

32 bit CRC

High

16 bit CRC

Low

GHz
Zigbee

10-200m

More than

868/915

25400

MHz
2.4GHz

2.5

Networking System

2.5.1

The Router

A router (including a wireless router) is a specialized networking device that


connected to two or more networks running software that allow the router to move

12
from one network to another. Router function in an internet protocol based network
operate at the network layer (OSI Model`s layer 3). The primary function of a router
is to connect network together and keep certain kinds of broadcast traffic under
control. This is a several companies that make router which is Cisco, Linksys,
Juniper, Netgear, Nortel (Bay Network), Dlink, Lucent, and Belkin.From the
previous projects, they used a router to connect two or more networks running
software to communicate each other. In [5], the device of the smart-home system is
connected each other using the wireless channel. The device of the smart-home has
ability to move, therefore their using the dynamical routing protocol to detect the
correct path when the original next hop has gone away so they can transfer data to
the corresponding nodes. In this smart-home system, the nodes can move and the
scale of this system is not small so they implement a routing protocol on Imote2. In
[5], they had described the process of routing protocol for the system. In [7], to make
the wireless network communication work efficiently they used topology of zigbee
wireless network.

Figure 2.1: Mesh network topology

13
Mesh topology is a network setup where each wireless modules and network
device are connected with each other. This network setup allowing the transmission
to be distributed to all wireless module or network device eventhought one of the
connection is down. Figure 2.1 shows the structure of the mesh topology network for
the zigbee module. Mesh topology, also referred to as peer-to-peer topology,
consisting of mesh routers and end devices. In [6], they used zigbee module as a
node to transfers the data wirelessly to the access point. Each node is usually
connected via at least two nodes and can transfer the information to its neighbors.
While in [8] they used mesh technology network where it can support the multi hop
transmission through nearby nodes. This approach was enable the node to transmit
the data even the node was far away from the access point by passing the data to the
neighbor nodes and the neighbor nodes will transmit to the access point.

There are several benefit of mesh network topology which is;

i. Flexibility can be achieved by simply adding more routers to the network.


Then, a new node is added automatically searches its neighbor nodes,
creating a proper way.
ii. This topology is very reliable and robust. When the router individuals
become inaccessible, alternative routes can replace the void.
iii. Network expansion is equally likely to use the tools intermediate in the
pathway.
iv. Each node communicates with nearby nodes, thereby reducing both network
disruption of long-distance communication and average power consumption.

2.6

System Implementation

Figure 2.2 shows the system implementation of the smart home system,
where it consists a hardware system, sensor node, home platform and user

14
interface.

Figure 2.2: System Implementation of the SmartHome

2.6.1

Hardware Platform system

In previous projects, there are several types of hardware design that their
proposed which is to monitor and control the home appliances. In [9], based on
figure 2.3, the researcher developed a power outlet module to control the home
appliance and it is composed of a zigbee compliant Radio Frequency (RF)
transceiver, a mainboard, and a power transformer. All this component are installed
in a plastic housing.

Figure 2.3: Structure Decomposition Of The Power Outlet Module

15
The zigbee or RF transceiver is connected with the mainboard by an
expansion connector and it works at the 2.4 GHz frequency band and establishes
wireless communication channel with other nodes in range.

In [10], the hardware system design is similar to the previous project but in
this design they used the embedded home server which is consist embedded platform
which had an 800-MHz intel processor , 512-MB RAM and 60-GB hard disk. Figure
2.4 and 2.5 show the structure design of the hardware which named as PPCOM.

Figure 2.4: Structured design inside of the PPCOM hardware

Figure 2.5: Structured design outside of the PPCOM hardware

The PPCOM using Programmable Logic Control (PLC) to enables the home
network user to connect a wide range of electric home appliances easily,thereby
eliminating the need of additional cabling to connect individual devices.

16
2.6.2

2.6.2.1

Sensor Nodes

ZigBee

In previous works, a lot of Smart Home system based wireless sensor


network using ZigBee Module. In [6] [7] [11] [12], they used a ZigBee wireless
network as a sensor nodes to send the data wirelessly to the access point or platform.
Futhermore, ZigBee has some technical advantages which are it kind of low power
consuming and has coverage area surrounded by 200 meter, with a data rate ranging
from 20Kbps to 250Kbps. Figure 2.6 shows the ZigBee wirelss network structure
where it able to support multi-hop wireless communication.

Figure 2.6: The model of ZigBee wireless network

In [13], the authors had summarized the different between XBee RF module
with XBee Wi-Fi RF module. From Table 2.3, we can see that the XBee Wi-Fi
module requires more transmitter power and supply voltage than XBee RF module.
On the other hand, the XBee Wi-Fi module has its own advantages of having a much
higher data rates compared to the XBee RF module. In addition to that, the XBee WiFi RF module is more robust and less susceptible to interference and this has made it
a good option for the project. The diagram of XBee RF and XBee Wi-Fi module are
shown in figure 2.7.

17
Table 2.3: Comparison XBee RF Module with XBee Wi-Fi RF Module

Specification

XBee RF Module

Protocol standard

IEEE 802.15.4

Suplly voltage

2.8 3.4 V

Transmitter Power Output

O dBm

RF Data Rate

250 kbps

XBee Wi-Fi RF
802.11 b, g, and n
3.1 3.6 V
>15dBm
802.11 b 1, 2, 5.5, and
11Mbps
802.11 g 6, 9, 12, 18, 24,
36, 48, and 54 Mbps
802.11 n 6.5, 13, 19.5, 26,
39, 52, 58.5, and 65 Mbps

Receiver sensitivity

-92 dBm

802.11 b 1Mbps -97dBm


(<8% PER)
802.11 b 2Mbps -93dBm
(<8% PER)
802.11 b 11Mbps -89dBm
(<8% PER)
802.11 g 6Mbps -91dBm
(<10% PER)
802.11 g 54 Mbps 75dBm (<10% PER)
802.11 n 65Mbps -72dBm
(<10% PER)

Indoor/Urban range

30 m

TBD

Outdoor RF line-of-sight

90 m

TBD

range

18

Figure 2.7: XBee RF Module and XBee Wi-Fi RF Module

2.6.2.2

nRF24L01 Single Chip 2.4GHz Transceiver

nRF24L01 module is a wireless communication device that contain sinle chip


2.4GHz transceiver with implanted broadband protocol engine designed for ultra-low
power applications access. This module was designed for operation in the wide world
of Industry, Scientifics and Medical (ISM) frequency band at 2.400 - 2.4835GHz.
For the radio system design using nRF24L01, it need a microcontroller such as
arduino uno to program the radio system design.

Futhermore, nRF24L01 module has a strip embedded protocol engine


(Enhanced ShockBurst ) that are based on packet communications, and supports a
variety of modes from manual operation to advanced autonomous protocol operation.
Internal FIFOs ensure a smooth flow of data between the front end of the radio and
MCU system. Enhanced Shock Burst reduces the cost of operating the system to
handle all the high-speed link layer.[13]. Table 2.4 shows the capabilities of
nRF24L01.

19
Table 2.3: nRF24L01 module capability

Features
Radio

Explanation

Worldwide 2.4GHz ISM band


operation

126 RF channels

Common RX and TX pins

GFSK modulation

1 and 2Mbps air data rate

1MHz non-overlapping channel


spacing at 1Mbps

2MHz non-overlapping channel


spacing at 2Mbps

Transmitter

Programmable output power: 0, -6,


-12 or -18dBm

Receiver

RF Synthesizer

11.3mA at 0dBm output power

Integrated channel filters

12.3mA at 2Mbps

-82dBm sensitivity at 2Mbps

-85dBm sensitivity at 1Mbps

Programmable LNA gain

Fully integrated synthesizer

No external loop filer, VCO


varactor diode or resonator

Accepts low cost 60ppm 16MHz


crystal

Enhanced ShockBurst

1 to 32 bytes dynamic payload


length

Automatic packet handling

Auto packet transaction handling

6 data pipe MultiCeiver for 1:6


star networks

Power Management

Integrated voltage regulator

20

1.9 to 3.6V supply range

Idle modes with fast start-up times


for advanced power management

22uA Standby-I mode, 900nA


power down mode

Max 1.5ms start-up from power


down mode

Max 130us start-up from standby-I


mode

Host Interface

4-pin hardware SPI

Max 8Mbps

3 separate 32 bytes TX and RX


FIFOs

5V tolerant inputs

From the previous project [14][15], the researcher had explained about the
analysis of the maximal transmission rate based on nRF24L01 chip system. The
whole transmission data format is shown in the Table 2.5.

Table 2.4 below shows the data format of the nRF24L01 chip where it has
32-bytes for the length of the whole frame which are icluded 3-5 bytes for the
address data and 0-2 bytes for Cyclic Redundancy Check (CRC). Balanced bytes was
the active data length.

Table 2.4: Data format of the nRF24L01 chip


Preamble

Address

Data

CRC

1 Byte

3-5 Byte

1-32 Byte

0-2 Byte

For the conclusion of this experiment, a good multi-chip system reduced


congestion in the system transmission rate and increase the transmission rate of
wireless transmission systems theory. As shown in Table 2.6, the new system has a

21
multi-chip transmission rate of about 6Mbps. This system allows to send high quality
images in the media wirelessly.

Table 2.5: Compare transmission rate of the multi-chip system

Number of

Overall data transfer rates

Rate (Compare to single

chips

chip)

6700Kbps

2Mbps

1.98

3.9Mbps

5.8

5.9Mbps

8.86

2.6.2.3

Bluetooth

In [16], the project using Bluetooth module as a communication module to


transfer the data wirelessly to the user. Bluetooth can provide point to point
connection or point to multipoint connections. However, Bluetooth module only
have 8 number of nodes to do point to point connection between them. Bluetooth
module also have a short distance range which is 10 meter and high consuming
power which is it not suitable to used in smart home power monitoring. From this
project to overcome the problem of limit number of nodes, they had discovered the
piconet network. In a piconet, only one main unit support up to seven affiliated unit,
which is active and established communication with the main unit, then support up to
255 affliated device which is park to keep pace. Several piconet are linked together
and rely on frequency-hoping sequence to identify each piconet. In the same piconet,
all user are synchronous with this frequency- hopping sequence.

22
2.6.3

Home Platform

The platform defines a standard around which a system can be developed.


Once the platform has been defined, software developers can produce appropriate
software and managers can purchase appropriate hardware and application. The term
is often used asa synonym of operating system.

In this paper[5], the hardware platform that was used is Imote2 node. Imote2
node is a product of Crossbow Technology, Inc. that is an advanced wireless sensor
node platform, which is built around the low power PXA271 XScale CPU and also
integrates an IEEE 802.15.4 compliant radio. The design of Imote2 is modular and
stackable with interface connectors for expansion boards on both the top and bottom
sides. The structure and details of the components are shown in Figure 2.8
respectively.

Figure 2.8: Structure of the hardware platform

Another previous project wich is in [13][17], they used a single set of raspberry pi
as a hardware platform. In this project they setup a raspberry Pi as an access point which is
intermediate system between the SmartHome device and hosting server. Figure below shows
a single set computer raspberry Pi.

23

Figure 2.9: A Single set computer Raspberry Pi

Figure 2.10: Dsecription of Raspberry Pi

Raspberry Pi shown in Figure 2.10 is single board computer developed in the


UK by Raspberry Pi foundation with the intention of stimulating the teaching of
basic computer science in schools. It has two models which are model A and Model
B as shown in Figure 2.9. Table 2.6 below shows the description of the madel A and
Model B.

24
Table 2.6: Discription about Model A and Model B of raspberry Pi

Raspberry Pi
Model A

Model B

has 256Mb RAM, one USB port and no has 512Mb RAM, 2 USB ports and an
network connection

Ethernet port

It has a Broadcom BCM2835 system on a chip which includes an ARMl176JZF -S


700 MHz processor, Video Core IV GPU, and an SD card. The GPU is capable of
Blu-ray quality playback, using H.264 at 40MBits/s. It has a fast 3D core accessed
using the supplied OpenGL ES2.0 and OpenVG libraries. The chip specifically
provides HDMI and there is no VGAsupport.

The foundation provides Debian and Arch Linux ARM distributions and also
Python as the main programming language, with the support for BBC BASIC, C and
Perl, detailed description of Raspberry Pi board has been given in Fig. 2.10. Python
was chosen as the main programming language, as it is generally accepted to be both
easy to learn and a fully fledged , programming language suitable for real world
applications. With the addition of NumPy, SciPy, Matplotlib, IPython, and PyLab,
Python can be used for computational mathematics as well as for the analysis of
experimental data or control systems[18].

Also, the recent development of the Raspberry Pi mini- computer has


unlocked great potential for computing to be applied in a vast number of areas. Due
to the unique advantages of the Raspberry Pi system, this technology holds great
promise for providing solutions within the developing world. This includes but is not
limited to education tools, especially the use of GPIO (General Purpose
Input/Output) which allows automated data acquisition and producing simple digital
control systems in a school laboratory setting. The most distinctive feature of the
Raspberry Pi when used for educational purposes is the GPIO module, which allows
interfacing with general purpose electronics [17][19].

25
2.6.4

User Intefaces

User interfaces is a medium for the user to interact with the system. This user
interface enables the user to setup the system or to see the output from the system. In
[7], the researcher was developed a user interface to interact the hardware device
with the user. They used the IOS application interface process which is by using the
apple or I-phone model the user as shown in Figure 2.11 that can interact with the
hardware device.

Figure 2.11: Application Programming Interface (API) of Smart Phones and web
browser.

While in [3], from the previous project the authors provide an intuitive user
interface for monitoring and controlling the smart environment. From this project the
authors have developed two user interfaces which are for the large scale display as a
computer screen, TV and other and for the mobile devices. The users can interact
with the system through the interface either used the stationary interface or poartable
interface which is mobile devices. Figure 2.12 shows the large scale display for the
user interface and Figure 2.13 shows the mobile interfaces.

.For each device, it displays the current consumption in watts, the cost per
hour, and is projected to cost more than a year using the average daily use of an
adjustable time. The cost is calculated taking into account the price of electricity,
which depends on the day. Use and cumulative costs of all device data is shown

26
below in figure 2.12. These values, as well as the values per device is updated every
second

Figure 2.12: Stationary Monitoring Device

For the mobile devices, user can directly access appliances using UbiLense.
Figure 2.13 shows an example of the UbiLense interaction concept. It recognizes
objects using image processing methods and display energy consumption
information about the device.

Figure 2.13: Mobile Device-

UbiLense
2.7

Summary

On this chapter, it discussed on the SmartHome deisgn system where it


included the element of the SmartHome system theory from the previous project. It
also briefly explain about the characteristic of wireless sensor network, networking
system, and system implementation. For the characteristic of wireless sensor network
there are several wireless module are highlighted and were discussed detail in this

27
chapter. For the system implementation there are divided into three dividion which
are

hardware

platform,

home

platform

and

user

interface.

CHAPTER 3

METHODOLOGY

3.1

Introduction

This chapter discuss about the approach to develop the smart home wireless
power monitoring system. The design approach has been divided into three phase;
system specification requirement, design implementation and verification. The first
phase is to find out the conceptual design requirement system through hardware and
software specification. The second phase is too design the smart home wireless
power monitoring system hardware and the platform of the system, the hardware
include the wireless communication and measuring current circuit while the platform
is to collect the measure data and store in the memory.

The third phase is to implement the networking communication protocol of


the smart home system and connection to the internet. The fourth phase is to
implement the user interface using web interface using adope dreamviewer and the
final phase is to verify the validity of the design via experimental system testing to
ensure that the Smart Home wireless power monitoring system meets the required
specification.

29

Figure 3.1: Project flow of system design

Figure 3.1 shows the project flow to design the smart home wireless power
monitoring system. The green box indicates the design flow of the smart home
power monitoring device and the communication protocol among the smart home
power monitoring sensors. The yellow box indicates the communication between the
smart home power monitor device and the raspberry Pi and the red box indicates the
communication part of the design of the all system development which is between
the smart home power monitor device, raspberry Pi and the user interfaces.

3.2

System Specification and Requirement

Smart Home architecture and specification depends on the type of sensor


nodes, communication protocol, web interface operating system and routing that will
be used. Figure 3.2 and figure 3.3 show the architecture of the Smart Home wireless
power monitoring system that has been proposed.

30
3.2.1

Hardware Specification

Table 3.1: Hardware specification for the Smart Home Wireless Power Monitoring
system
No.

Device type

Function

Arduino Pro Mini

As a microcontroller or platform of the system

Voltage regulator

Convert 240V to 5V for supply to arduino pro mini

Current sensor

Measure the current consume

(ACS712)
4

nRF24L01

As wireless communication modules

Single Set

As a access point where all the data from smart home

Computer

power monitor will be send to raspberry Pi and save

Raspberry Pi

the data in database in raspberry Pi

Table 3.1 provides a hardware specification of the Smart Home Wireless


Power Monitoring system. For the smart home power monitoring it contain arduino
pro mini as a microcontroller where the current sensor and nRF24L01 wireless
module will attach on it. The current sensor will tapped on each main circuit breaker
(MCB) at distribution board at home. For example, if the distribution board had 8
MCB so we need 8 current sensors to measure the power consume in each MCB.
Arduino pro mini will receive the reading of all the data and send the data to access
point through RF wireless module which is nRF24L01. The raspberry Pi will receive
the data and save the data in database. The voltage regulator is used to convert the
240V power supply to 5V to give power to the arduino pro mini because the power
is directly taken from the distribution board. Figure 3.2 shows the system
architecture of smart home wireless power monitoring system device.

31

Figure 3.2: System Architecture Of Smart Home Wireless Power Monitoring System

device

3.2.2

Software Specification

Table 3.2: Software specifications information

No.

Component

1.

Single Set Computer

1) Linux as operating system

Raspberry Pi

2) MySql

Laptop

1) Arduino

2.

Software configuration

2) Xamp (Mysql,Apache)
3) Adope webviewer

Table 3.2 provide software specifications information used in the Smart


Home Wireless Power Monitoring system. Single set computer raspberry Pi is used
as an access point to receive the sensor data and save the data in database. To make
the raspberry Pi more compatible and efficient it needs an operating system (OS) that
enable the computer hardware to communicate and operate with the computer
software. Without a computer OS, a single set computer raspberry Pi and software
programs would be useless. For the OS of raspberry Pi, Linux will be used as an
operating system.

32
Linux is an operating system where the software on a computer that enables
applications and the computer operator to access the devices on the computer to
perform desired functions. The processor performs the instructed task, then sends the
results back to the application via the operating system [20]. Linux, which began its
existence as a server OS and has become useful as a desktop OS, can also be used on
all of these devices. From wristwatches to supercomputers, is the popular
description of Linux' capabilities.

After receive data from smart home power monitor, the data sensor will be
save in database. In this system the database was created using the MySQL database
software. MySQL is the world's most popular open source database software, with
over 100 million copies of its software downloaded or distributed throughout its
history. With its superior speed, reliability, and ease of use, MySQL has become the
preferred choice for Web, Web 2.0, SaaS, ISV, Telecom companies and forwardthinking corporate IT Managers because it eliminates the major problems associated
with downtime, maintenance and administration for modern, online applications
[21]. Table 3.3 shows the advantages of using the MySQL database.

Table 3.3: Advantages using MySQL

Advantages
i. MySQL is a database management system.
ii. MySQL software is Open Source.
iii. The MySQL Database Server is very fast, reliable, scalable, and easy
to use.
iv. A large amount of contributed MySQL software is available.

In general, XAMPP is used for web development on the local machine, as


opposed to directly on the web space. It allows to test out changes on the personal
computer before making those changes publicly online. The XAMPP package is
simply an easy way to install all the vital web server parts all at once, though its just
as possible to install them all individually and by hand instead[22].

33
XAMPP is Free and Open Source Cross-Platform Web Server Solution
Stack. It comes with Apache Web Server, MySQL Database, PHP and Perl
Programming Languages. Together with these there is an SMTP and FTP server
included as well.

3.3

System Design

A Smart Home wireless power monitoring system is a project which is to


develop a hardware device and software application that can be used by user to
monitor their power usage at home by connected the distribution board at home to
the smart power monitoring device by tapping the current sensor in each main circuit
breaker (MCB). It can measure the power consumed of the home appliance and send
the sensor data to the access point through the wireless communication. The access
data will received the sensor data and store the data at database. Figure 3.3 shows the
smart home wireless power monitoring system design.

For far distance communication, the web based for Smart Home Wireless
Power Monitoring system will be built. Therefore, it will need more data storage.
The alternative way is using the MySQL database. By using this software, data
storage space can be saved. The user can easily monitor their power consume by
connected to the internet using computer, laptop or Smartphone and directly can
monitor their power usage. The user also can analyze the data by see the graph at
web page that automatically draw every 10 seconds updated. The user can monitor
their power consumption at anywhere as long as they have internet connection. With
the aid of web page the user can see the performance of the power consumption
every time or weekly and it depend on user when they want to monitor their power
consumed. Furthermore, the user also can directly see their power consume in ringgit
Malaysia and it rate was follow the TNB tariff.

34

Figure 3.3: The Smart Home Wireless Power Monitoring System Design

Based on the flow chart in Figure 3.4, the overall design starts by setting up
the Raspberry Pi as the access point (AP). Then, the Raspberry Pi was put in the
listening mode and continuously waits for the sensor to send the message sensor
packet. When message packet has been received, the Raspberry Pi saves the data in
the database and synchronizes it with web page. A user in the home network can
have a direct access to the Raspberry Pi to get the access data. However, if the user
was in a remote area, the data can also be accessed but through the internet
connection by login at the smart home page.

The smart home wireless power monitoring system has been divided into
three part for a detailed optimization design. The first part is a smart home power
monitoring, the second is raspberry Pi as a access point and web page as a GUI for
user.

35

Start
Setup raspberry Pi
Access point
Database

Raspberry Pi
in listening mode

Sensor sent
the message
packet

Sensor data save in


database
User at outside request
service
User get service from
database

End

Figure 3.4: Flow chart system design

36
3.3.1

Home Network

Referring to the flowchart as shown in Figure 3.5, this smart home wireless
power monitoring system consist of three part which is first part is a smart home
power monitoring system, second part is a raspberry Pi as anaccess point and the last
part is a web page as a GUI for user. For the first part, the radio frequency module
will be initialize and setup it configure RF radio. The packet data of the RF module
was divided in a message packet and each message packet contain its own data. The
current sensor will measure the current consume and the data will be inserted into
the message packet before it will be send to the access point. The data type in
message packet need to be converted to char because message packet was in char
format and the current sensor data was in float type. After that, the data will send to
the access point.

37

Figure 3.5: Flow chart of Home Network

38
3.3.2

Configuring a Single Set Computer Raspberry Pi as a access point (AP)

Raspberry Pi was used as access point where it is a intermediate between the


SmartHome power monitoring device and the SmartHome web page. Before it can
be set as access point the raspberry Pi need to install the operating system on SD
card. After that, we just inserted the SD card in the raspberry Pi and turn on it.

The operating system name for Raspberry Pi is Raspbian Debian Wheezy


that can be download at Raspberry Pi official web site in images file. The Raspbian
is a free operating system for Raspberry Pi and it based on Linux. To install
Raspbian images on SD card need to use image writing tool such as Win32 Disk
Imager utility as shown in Figure 3.6.

Figure 3.6: Win32 Disk Imager software windows interface

After complete install Raspbian on SD card. Boots up the Raspbian using


Raspberry Pi and log in using Raspbian default username that is pi and default
password that is raspberry. Then to install software at Raspberry Pi we need to open
the Terminal software as shown in Figure 3.7.

39

Figure 3.7: Terminal software Linux interface

Figure 3.7 above shows the terminal of the raspberry Pi. Firstly, we need to
install the GPIO driver. This driver was used to control the GPIO pin at the raspberry
Pi. GPIO stand for general purpose input and output. Command as follows shows the
initial step to install GPIO driver on raspberry Pi.

sudo apt-get update


sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio
#add this two modules: i2c-bcm2708 i2c-dev
sudo nano /etc/modules
sudo apt-get install python-smbus
sudo apt-get install i2c-tools
# do COMMENT the lines with spi and i2c modules
sudo nano /etc/modprobe.d/raspi-blacklist.conf

Next, download the nRF24L01 library for raspberry Pi. To download the
nRF24L01 library on the raspberry Pi we need to install the github software at the
Githup web . After that, install the nRF24L01 library at raspberry Pi terminal. The
command as follows shows the step to install the library at the terminal.

40
#install git
sudo apt-get install git
#move to home
cd ~
#clone the RF24 repos
git clone https://github.com/stanleyseow/RF24

After done download nRF24L01 library, the nRF library is installed by write
the command in Terminal as shown as follows.

cd ~/RF24/librf24-rpi/librf24
#maybe you need to install build-essential
sudo apt-get install build-essential
make
sudo make install
sudo ldconfig -v | grep librf
librf24.so.1 -> librf24.so.1.0
#let's compile the examples
cd ../examples/
make

To compile the source code we need to wrote the command in c++ language
at the raspberry Pi terminal and then compile the command. The step to compile is
shown as follows.

cd ~/RF24/librf24-rpi/librf24/examples
g++ -Wall -Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk mtune=arm1176jzf-s -L../librf24/ -lrf24 `mysql_config --libs
--cflags`smarthome.cpp -o smarthome

To make the source code of access point in smarthome.cpp run automatic


after boots up the Raspberry Pi by write commnad in Terminal as shown below.

41
#create folder
mkdir ./bin
cd ./bin
#create script
sudo nano script_auto_run
#write this script in nano editor
#!/bin/bash
# Script to start our application
echo "Doing autorun script..."
sudo /home/pi/RF24/librf24-rpi/librf24/examples/smarthome
#save the script by pressing Ctrl+O and exit by pressing Ctrl+X
#made this script executable
sudo chmod 755 script_auto_run
Setting it to be automatic run
sudo nano /etc/rc.local
#add the this script inside rc.local
/home/pi/bin/script_auto_run
#save the script by pressing Ctrl+O and exit by pressing Ctrl+X
#reboot Raspberry Pi
sudo reboot

3.3.3

Developing the database and smart home web page for user interface.

To achieve the main objective of this project, the developing of the web page
was very important because it enable the user to monior their power consume at
smartphone or computer. To design the SmartHome web page we used the XAMP
software as shown on Figure 3.8. The specification of this software was discussed at
software specification above.

42

Figure 3.8: XAMPP software windows interface

To show the power consume at the webpage we need something that can
store the current sensor data. In this case, we had created a database using MySQL
software. The function of this database is to store all the current sensor data and the
data will be called back when needed. Flow chart as shown in Figure 3.9 shows the
flow of the SmartHome web page and database.
Start

Access point in
listening mode

AP will receive
current sensor data

Save the sensor data in


database

User login at the


SmartHome web page

Data at databse will be


call when needed

End

Figure 3.9: Flowchart of the database


and SmartHome web page

43
After done created the database for SmartHome power monitoring system,
next step is to design the SmartHome web page. For the designing of the web page
we used Adobe Dreamweaver CC to create the interface for the web page.

The web template is used from Zurb Foundation web site. The special of this
templateis it make the content of web page follow the screen size. The web page
consist of log in page and smart switch page.

3.4

Summary

SmartHome Wireless Power Monitoring system design has been divided into
three phase; system specification requirement, design implementation and
verification. The first phase is to find out the conceptual design requirement system
through hardware and software specification. The second phase is too design the
smart home wireless power monitoring system hardware and the platform of the
system, the hardware include the wireless communication and measuring current
circuit while the platform is to collect the measure data and store in the memory.
Lastly, is the system verification in term of experimental performance and
functionality of the SmartHome Wireless Power Monitoring system.

CHAPTER 4

RESULTS

4.1

Introduction

The essential goal of this project is to achieve the most robust accurate
algorithm to measure the current sensor in real time, convert the current consume
into power and calculate the power consume according to the TNB tariff. The result
of the project includes the setup and configuration of the Smart Home Wireless
Power Monitoring System and smart home web based user interface. The results are
divided into three parts which are the smart home power monitoring device, the
communication between AP and smart home power monitoring device, and finally
the communication between AP and the smart home web based. Figure 4.1 shows
the full setup of the Smart Home Wireless Power Monitoring system hardware and
Smart Home web page.

45

Figure 4.1: Full Setup of Smart Home Wireless Power

Monitoring System

4.2

Setup current sensor ACS712

Figure 4.2 (a) shows current sensor used for measured the current consume in
the Smart Home Wireless Power Monitoring system. Figure 4.2 (b) shows the serial
monitor of the current sensor when no load tapped to the current sensor.

Figure 4.2: Current sensor ACS712 and arduino

46
The figure 4.3 shows analog read serial command to reads an analog input
from current sensor and print the result to the serial monitor. The current sensor
ACS712 has an offset value which means it have value even though no load attach to
the current sensor. It is important step to know the offset value of the current sensor
before calculate the current sensor reading. For the rest of the soft code will be
shows in Appendix A.

Figure 4.3: Analog read serial command to reads an analog input from current sensor

Figure 4.4 (a) shows the Smart Home Power Monitoring device that is used
in the Smart Home Wireless Power Monitoring system. Figure 4.4 (b) shows the
prototype of the Smart Home system at home.

47

Figure 4.4: Smart Home Wireless Power monitoring system

Figure 4.5 below shows the wiring connection between the current sensor
and the main circuit breaker (MCB). In this prototype of the Smart Home system the
MCB in the distribution board (DB) only have three units therefore for the smart
home power monitoring device also have three units. Each of the current sensor ACS
712 will be tapped in the each MCB using the PVC wire cable as shown in figure
4.5. In the real product the number of current sensor will depend on the number of
MCB in the DB at home. Each current sensor will measured the power consume on
each MCB and send the data to the access point wirelessly through the RF module
which is nRF24L01.

48

Figure 4.5: Wiring of the smart home power monitoring device with main
circuit breaker (MCB)

4.3

Setup the raspberry Pi as access point (AP)

Figure 4.6: A single set computer Raspberry Pi

Figure 4.6 above shows the raspberry Pi and the RF module which is
nRF24L01. The RF module is connected through the GPIO pin at the raspberry Pi.
The connection of the RF module at the GPIO pin as shown in Figure 4.7.

49

Figure 4.7: The connection between the Raspberry Pi and the


nRF24l01 module

After make a connection between the RF module and the raspberry Pi, the
access point now will be able to receive the data from the smart home power
monitoring device. The data received then will save in the database. The next subtitle
will discuss about the operation between the access point and smart home power
monitoring device and the database.

50
4.3

Result Communication between smart home power monitor and Access


Point

Figure 4.8: Smart home wireless power monitoring system prototype and AP

Figure 4.8 (a) shows the smart home wireless power monitoring system
prototype had been tested using the water heater and figure 4.8 (b) shows the
raspberry Pi as an access point. The smart home power monitoring device as shown
in figure 4.8 (a) will measure the current consume of the water heater and send the
sensor data to the access point wirelessly through RF module.

51

Figure 4.9 shows the data receive from the smart home power monitoring device.
Figure 4.9: Data received from smart home power monitoring
The water heater was plug in at the sensor number two. From figure 4.9, we
can see that the sensor one show zero reading and sensor three shows almost zero
reading. The power_2 is the reading for the water heater in kWs because the data
will be sends every one second.

4.4

Result Communication between Access Point and database

After communication between the smart home power monitoring device and
access point is established, the next step is to save the sensor data received into the
database. The code below show the step to link the data receive to the database. The
rest of the source code will be shown in Appendix A.

First step is we need to declare the library that is used in the coding. All the
declarations are as shown as follows.

52
/*-----( Connecting to mysql )-----*/
#include <mysql/mysql.h> // MySQL Include File
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "admin"
#define DATABASE "smarthome"

When the access point received data from smart home power monitoring
device, this command will activate just after the data received. This code will create
a pointer to the MySQL instance.

MYSQL *connect; // Create a pointer to the MySQL instance


connect=mysql_init(NULL); // Initialise the instance

connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DAT
ABASE,0,NULL,0);

memset(query,0,sizeof(query));

Before the data received is inserts into the database, the data will be
converted to the character type. This code as follows shows the command to convert
the data receive in float type to the character type.

53
sprintf(query, "INSERT INTO
powermonitor(powerconsume1,powerconsume2,powerconsume3,
currentconsume1,currentconsume2,currentconsume3,
costrm1,costrm2,costrm3,totalcostrm,time ) VALUE
(%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,NOW())",power_1,power_2,power_3,
rms_1,rms_2,rms_3,rm_A0,rm_A1,rm_A2,rm_total);

memset(query,0,sizeof(query));

sprintf(query, "UPDATE smarhome.powermonitortotal SET


powerconsume1=%f,powerconsume2=%f,powerconsume3=%f,currentco
nsume1=%f,currentconsume2=%f,currentconsume3=%f,costrm1=%f,cos
trm2=%f,costrm3=%f,totalcostrm=%f, time=NOW() WHERE
powermonitortotal.power_id='1'",power_1,power_2,power_3,rms_1,rms
_2,rms_3,rm_A0,rm_A1,rm_A2,rm_total);

After done inserting the data receive into the database, the MySQL
connection will be close and the MySQL will in mode listening to the next event.
Code as follows show the command to close the MySQL connection.

mysql_close(connect);

Figure 4.10 shows the database of the smart home system. All the data
receive will be saved in the database. The data will refer to the number of sensor id.
For example, for sensor id one the data will be saved in power consumed 1 and the
rest will be saved according to the sensor id. The results are shown as in figure 4.10.

54

Figure 4.10: Database of the smart home system

4.5

Result Communication between Access Point and smart home web page

Figure 4.11 shows the Smart Home login page. For the Smart Home web
page GUI the user need to login to the system to get access the data. After
successfully login into the system the user can go to the display option and choose
the power consumption as shown in figure 4.12. Then user can see their power
consumption in graph type as shown in figure 4.13. The user also can see the value
of the total power consumption in ringgit Malaysia according to the TNB tariff. The
result shows at figure 4.14.

Figure 4.11: Smart Home WEB page login system

55

Figure 4.12: Smart Home GUI interface

Figure 4.13: Power consumption graph

56

Figure 4.14: Value power consume in ringgit Malaysia

4.6

Summary

This chapter discussed on SmartHome Wireless power Monitoring system


result based on the experimental. On this chapter we have divided into five
experimental result which are included setup current sensor ACS712, setup the
Raspberry Pi as an access point (AP), the result of communication between
SmartHome power monitoring device and access point, the result communication
between access point and database and lastly the result communication between
access point and SmartHome web page.

CHAPTER 5

DISCUSSION

5.1

Introduction

This chapter briefly discusses on the result obtained from experiment and
also highlights the problems faced during the progression of this project. The result
of the project includes the setup and configuration of the Smart Home Wireless
Power Monitoring system and Smart Home Web Based interface.

5.2

Getting accurate reading of the current sensor

Using the ACS712 current sensor to measure the current value is a challenge
work because the reading from the current sensor was different when we used
different code to set the current sensor. Figure 5.1 shows the experiment tested to
calibrate the reading of the current sensor. For the reference reading we used clamp
meter to compare with the experiment reading as shown in figure 5.1 (b).

58

Figure 5.1: Experiment result measured the current

The code as follows shows the step to read the ACS712 current sensor
module. The example of the soft code of this current sensor was found in the
previous project. The soft code is for measured the direct current (DC) only and in
my project we want to measure the alternating current (AC) so, the soft code need to
change to get the AC current value. The code bellow shows the step to measure the
AC current.

void loop()
{
unsigned long currentAcc = 0;
unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)
{
if (micros() - prevMicros >= sampleInterval)
{
int adc_raw = analogRead(currentPin) - adc_zero;
currentAcc += (unsigned long)(adc_raw * adc_raw);
++count;
prevMicros += sampleInterval;
}
}
float rms = (sqrt((float)currentAcc/(float)sampleInterval) * (75.7576 / 1023.0)) -0.06 ;
Serial.println(rms);
delay (250);
}

59
To calibrate the reading sensor to get the nearest value with the reference
reading, we just change the value that was highlighted at the previous code. The
value is choosing by record the reading value when no load was attach to the current
sensor. Then the reading value was taken and put the value on the code as shown at
previous code to get zero reading when no load was attach.

Figure 5.2: Current sensor value when no load

This reading is accepted because the value almost nearest to zero when no
load is attach. When the current sensor attach to the load the value of the current
sensor was not accurate and the current sensor reading is fluctuate. For this
experiment we use lamp as a load to the current sensor. Figure 5.3 show the
experiment procedure and figure 5.4 shows the result from the current sensor.

60

Figure 5.3: Experiment procedure

Figure 5.4: current sensor reading with load

To overcome this problem we try to take several samples of the current


sensor reading and average the reading. To get more accurate reading we try to find
another code at the previous project that used the current sensor ACS712. Finally we
found the almost accurate reading of the current sensor. The flow chart as shown in

61
figure 5.5 shows the step to read the current sensor. The rest of the source code will
be shown in Appendix A.

Figure 5.5: Step to read the


current sensor

62
5.3

Create wireless protocol transmits and receives between the Smart


Home power monitoring device and access point (AP)

The second problem was to create the wireless protocol between the Smart
Home power monitoring device and access point (AP). In this Smart Home Wireless
Power Monitoring system, we setup the Smart Home Power Monitoring device as a
transmit device and the raspberry Pi as a receive device. In the previous project the
author used zigbee module as a wireless module. For our project we used the RF
module which is nRF24L01 as a wireless module to transmit and receive data or also
known as transreceiver module. We use the RF module because the price is cheaper
than the ZigBee module. The initial problem during construct the wireless
communication protocol is the problem with the sensor data packet. The
communication between the Smart Home Power Monitoring device and access point
(AP) was successful. Both can can communicate each other but the packet data send
was lost at the access point. The access point was receive the message packet but the
sensor data was zero reading eventhought it have reading. After troubleshoot the
code we found that the message packet size was not enough to insert the sensor value
into the message packet and to transmit the message packet we cannot send the
sensor value in the float type. The solution to this problem is we increase the size of
the message packet and to transmit the sensor value firstly convert the sensor value
to character and then insert into the message packet. When the access point receive
the message packet the sensor value will be convert back to float type.

5.4

Insert the receive data into the database

After receive the sensor value from the Smart Home Power Monitoring
device, the sensor value will be store into the database. The problem is the sensor
value was not store in the database. During the experiment, the Smart Home Power
Monitoring device was apply on the water heater and this device send the sensor
value to the access point. The expected result is the access point will receive the
sensor value and then the sensor value will be store into the database but after a
while the database still not update the sensor value data.

63
After troubleshoot the code, we found that it cannot stored the sensor value in
float type same as in the wireless protocol transmits and receives between the Smart
Home power monitoring device and access point (AP).

The solution is we convert the float type into character and then stored the
sensor value into the database. The code as shown in figure 5.6 is the command to
convert the float type to the character.

Figure 5.6: command to convert the float type to the character.

5.5

Summary

This chapter discussed on SmartHome Wireless power Monitoring system


problem and solution that was based on the experimental result. There are the main
three problem that was discussed in this chapter which were the problem to get
accurate reading of the current sensor, to create wireless communication protocol
transmits and receives between the SmartHome power monitoring device and access
point (AP) and the last problem was to insert the receives data from SmartHome
power monitoring device into MySQL database. In this chapter, we also discussed
briefly about the solution of the problems.

CHAPTER 6

CONCLUSION

6.1

Introduction

This chapter briefly discusses about the conclusion and recommendation for
future improvements to enhance the Smart Home Wireless Power Monitoring system
based on Wireless Sensor Node and Smart Home web page

6.2

Conclusion

In conclusion, a working Smart Home system has been developed using a


arduino Pro mini as a microcontroller to the ACS712 current sensor and nRF24L01
wireless module, a single set computer Raspberry Pi , MySQL database and Smart
Home Web page. The Raspberry Pi acts as the server, and has been setup becoming
the access point. The use of Raspberry Pi has solved the cost and bulkiness of the
previous server. The user can access through the system data with the simple use of a
smart phone or laptop at everywhere as long they have the internet connection.
Therefore it is compatible to be used on any platform and types of Smartphone,
because nowadays in the markets have a various type Smartphone.

65
On the other hand, in this SmartHome system we have build a user interface
for the convenience of the user. The user can easily login in the SmartHome web
page and access the data of power consumption. In the power consumption page also
we had provide the total power consumed into the ringgit Malaysia according to the
TNB tariff.

For further development, the Smart Home system can be commercialized in


many applications. The system able to monitoring and surveillance home, so that the
system can be applied for monitoring senior citizens daily life and home security

6.3

Limitation and Recommendation for Future Works

There are several recommendations that can be made to improve this Smart
Home Wireless Power Monitoring System. This is the list of recommendations can
be considered for future works which are;

i. Selection of the current sensor,


ii. Wireless communication protocol between wireless sensor network to the
Raspberry Pi server and
iii. Database in Raspberry Pi.

CHAPTER 7

PROJECT MANAGEMENT

7.1

Introduction

The objective of the project management is to achieve all project goals with
effective project planning, organizing, and controlling resource within a specified
time period. The primary constraints in this project are the research scope, research
time, research budget and human resource to perfom the required activity. Based on
the stated constraints, project schedule had been tabulated on Gantt chart which it
gives a clear guidline I time management of this project.

Next, cost estimation on the components is perfomed to ensure minimal


project cost while keeping project to achieve the required requirement. In this
process, market survey on different electronic supplier is carried out; component
price is the tabulated to compute the final cost.

7.2

Project Schedule

Table 7.1 shows project Gantt chart for semester one. Table below shows the
flow of work progress during the semester one. For the first week all the final years
student must attend briefing for FYP I and FYP II that given by FYP coordinator, En
Muhammad Arif bin Abdul Rahim This was important to final year student complete
their project without any problem. Besides that, it shows that there was late start in

67
literature review, because of the faculty late assign project supervisor to student.
While other task was commences as proposed on date, with exception of project
initial report writing that lag behind 1 week.

Table 7.2 shows project Gantt chart for semester two. In contrast to Gantt
chart semester two, Gantt chart in second semester showed an expected long delay in
some task at end of the project schedule. The delay on construction of hardware was
due to late arrival of electronic components sent from supplier and PCB fabrication
at PCB Lab. As PCB boards and electronic component was the backbone of
electronic circuits, so other task such as components assembling and design
verification were postponed.

68

Table 7.1: Project Gantt Chart (Semester One)


No

Week
Activities

1.

Briefing for
FYP

2.

Literature
Review

3.

Research
Methodology

4.

Market analysis

5.

Study Arduino
Pro Mini
microcontroller

6.

Simulate
Arduino Pro
Mini Code &
Design Circuit

7.

Submit proposal

8.

Type of current
sensor

9.

Hardware
design

10.

Circuit design

11.

Report
preparation

12.

Presentation
FYP1

10

11

12 13

14

15

69
Table 7.2: Project Gantt Chart (Semester Two)
No

Week

10

11

12 13

14

15

Activities
1.
2.
3.
4.

5.
6.
7.

8.
9.

Literature and
theoretical study
Construction of
hardware
Programming
Arduino
Programming
Processing
software
Run the
Experiment
Modification
and Evaluation
Result,
Discussion and
Conclusion
Presentation
Report
preparation

7.3

Cost Estimation

Table 7.3 shows the cost estimation for assembling the hardware prototype.
The hardware prototype is used to support the smarthome system. The most
expensive in this hardware prototype are insulator 32A and plywood. All the price
are shows in the table 7.3.

Table 7.4 shows the cost estimation for assembling the SmartHome power
monitoring device. The most expensive in this board is Arduino Pro Mini and the
voltage regulator (240V-5V). Arduino Pro Mini is use as a micro-controller in
thisboard to control the current sensor and nRF24L01. The voltage regulator is used
to convert 240V power supply from home to 5V to give supply to the Arduino Pro
Mini.

70
Table 7.3: Hardware cost estimation
No.

Item

1.

Distribution

Picture

Price

Quantity

Total

RM 6.00

RM6.00

RM3.00

RM9.00

PVC wire 2.5

RM1.50

3m

RM4.50

(green)

permeter

PVC wire 2.5

RM1.50

3m

RM4.50

(red)

permeter

PVC wire 2.5

RM1.50

3m

RM4.50

(black)

permeter

6.

Connector

RM1.00

RM1.00

7.

Perspex

RM10.00

RM10.00

8.

Insulator 32A

RM12.00

RM12.00

9.

Switch

RM3.50

RM3.50

10.

Lamp filament

RM2.00

RM2.00

11.

Lamp holder

RM2.50

RM2.50

12.

Plywood

RM15.00

board casing
2.

Main circuit
breaker

3.

4.

5.

RM15.00

RM74.50

71
Table 7.4: Electronic component cost estimation

No.

Item

Price

Quantity

Total

1.

Arduino pro mini

RM11.00

RM11.00

2.

Current sensor

RM7.00

RM21.00

3.

nRF24L01

RM3.50

RM3.50

4.

Voltage regulator(3.3V)

RM5.00

RM5.00

5.

Capacitor

RM0.07

RM0.20

6.

Voltage regulator

RM10.00

RM10.00

(240V-5V)
7.

Switch

RM2.50

RM2.50

8.

Pin header

RM0.70

RM1.40

9.

Solder lead

RM3.50

RM7.00

TOTAL

RM61.60

72

References

[1]

C. Buratti, A. Conti, D. Dardari, and R. Verdone, An overview on wireless


sensor networks technology and evolution., Sensors (Basel)., vol. 9, no. 9,
pp. 686996, Jan. 2009.

[2]

I. Pembekalan and E. Di, Industri pembekalan elektrik di malaysia, 2011.

[3]

M. Jahn, M. Jentsch, C. R. Prause, F. Pramudianto, A. Al-akkad, S.


Birlinghoven, and S. Augustin, The Energy Aware Smart Home, pp. 07,
2010.

[4]

T.-S. Choi, K.-R. Ko, S.-C. Park, Y.-S. Jang, Y.-T. Yoon, and S.-K. Im,
Analysis of energy savings using smart metering system and IHD (in-home
display), 2009 Transm. Distrib. Conf. Expo. Asia Pacific, pp. 14, Oct. 2009.

[5]

X. Tang, C. Xu, M. Wu, and J. Wen, A DESIGN OF SMART-HOME


STSTEM BASED ON 6LOWPAN WIRELESS SENSOR NETWORKS.

[6]

N. Javaid, A. Sharif, A. Mahmood, S. Ahmed, U. Qasim, and Z. A. Khan,


Monitoring and Controlling Power using Zigbee Communications, 2012.

[7]

H. Shang and R. Xu, A Smart Home System Based On ZigBee And IOS
Software, pp. 37, 2012.

[8]

M. A. B. Sarijari, R. a. Rashid, M. R. A. Rahim, and N. H. Mahalin,


Wireless Home Security and Automation System Utilizing ZigBee based
Multi-hop Communication, 2008 6th Natl. Conf. Telecommun. Technol.
2008 2nd Malaysia Conf. Photonics, pp. 242245, Aug. 2008.

[9]

G. Song, F. Ding, W. Zhang, and A. Song, A wireless power outlet system


for smart homes, IEEE Trans. Consum. Electron., vol. 54, no. 4, pp. 1688
1691, Nov. 2008.

[10] C.-H. Lien, H.-C. Chen, Y.-W. Bai, and M.-B. Lin, Power Monitoring and
Control for Electric Home Appliances Based on Power Line
Communication, 2008 IEEE Instrum. Meas. Technol. Conf., pp. 21792184,
May 2008.
[11] M. Kang, Y. Ke, S. Member, and J. Li, Implementation of Smart Loading
Monitoring and Control System with ZigBee Wireless Network, pp. 907
912, 2011.
[12] V. Nuhijevic, S. Vukosavljev, and B. Radin, An Intelligent Home
Networking System, pp. 4851, 2011.

73
[13] A. Aizat and B. I. N. Mohd, SMART HOME USING WIRELESS SENSOR
NETWORK AND ANDROID POWERED DEVICES UNIVERSITI
TEKNOLOGI MALAYSIA.
[14] P. Christ, B. Neuwinger, F. Werner, and R. Ulrich, Performance Analysis of
the nRF24L01
Ultra-Low-Power Transceiver in a Multi-Transmitter and Multi-Receiver Scenario,
pp. 36, 2011.
[15] Y. Liu and X. Han, Analysis of the Maximal Transmission Rate Based on
nRF24L01 Chip System, 2010 2nd Int. Conf. Inf. Eng. Comput. Sci., pp. 13,
Dec. 2010.
[16] D. Society, W. Ting, G. Chenjie, Z. Jia, and Y. Wei, Wireless monitoring
system based on Bluetooth smart phones, 2010 Int. Conf. Netw. Digit. Soc.,
pp. 648651, May 2010.
[17] A. C. D. Bonganay, J. C. Magno, A. G. Marcellana, J. M. E. Morante, and N.
G. Perez, Automated electric meter reading and monitoring system using
ZigBee-integrated raspberry Pi single board computer via Modbus, 2014
IEEE Students Conf. Electr. Electron. Comput. Sci., pp. 16, Mar. 2014.
[18] a. R. Al-Ali and M. AL-Rousan, Java-based home automation system, IEEE
Trans. Consum. Electron., vol. 50, no. 2, pp. 498504, May 2004.
[19] S. Jain, A. Vaibhav, and L. Goyal, Raspberry Pi based Interactive Home
Automation System through E-mail LED ( Switch (, no. 2002, pp. 277280,
2014.
[20] M. Garrels, Introduction to Linux A Hands on Guide Table of Contents,
2008.
[21] A. Mclysaght, Introduction to MySQL.
[22] W. Xp, Test Run Installation Instructions.

74
APPENDIX A

SmartHome Power Monitoring device soft code

//SmartHome Wireless Power Monitoring System


//NRF24L01 Communication Module
//Main code
/*
1 - GND
2 - VCC 3.3V !!! NOT 5V
3 - CE to Arduino pin 8
4 - CSN to Arduino pin 9
5 - SCK to Arduino pin 13
6 - MOSI to Arduino pin 11
7 - MISO to Arduino pin 12
8 - UNUSED */
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
#include <stdio.h>
#include <stdlib.h>
#define CE_PIN

#define CSN_PIN 9
RF24 radio (CE_PIN, CSN_PIN);
// Radio pipe addresses for nodes to node communicate.
const

uint64_t

pipes[2]

0xF0F0F0F0E1LL,

0xF0F0F0F0D2LL };
char message[32]; // message payload 32byte 0-31
int ds = 7; //datsize
//char str[24]; // str[data size]

75
int sensorStatus;
/*<<<<<<<<<<<<<<<currentsensorparameter>>>>>>>>>>>*/
const unsigned long currentPin_A0 = A0;
const unsigned long currentPin_A1 = A1;
const unsigned long currentPin_A2 = A2;
const

unsigned

long

sampleTime

100000UL;

// sample over 100ms, it is an exact number of cycles


for both 50Hz and 60Hz mains
const

unsigned

long

numSamples

250UL;

// choose the number of samples to divide sampleTime


exactly, but low enough for the ADC to keep up
const

unsigned

sampleTime/numSamples;

long

sampleInterval

// the sampling interval, must

be longer than then ADC conversion time


long adc_zero_A0 = 0; // relative digital zero of the
arudino input from ACS712 (could make this a variable
and auto-adjust it)
long adc_zero_A1 = 0;
long adc_zero_A2 = 0;
int adc_raw_A0;
int adc_raw_A1;
int adc_raw_A2;
int sensorValue_A0;
int sensorValue_A1;
int sensorValue_A2;
int x_A0 = 0;
int z_A0 = 0;
int x_A1 = 0;
int z_A1 = 0;
int x_A2 = 0;
int z_A2 = 0;
float rms_A0=0;
float rms_A1=0;
float rms_A2=0;
float rms_i_A0=0;
float rms_i_A1=0;

76
float rms_i_A2=0;
float rms_1=0;
float rms_2=0;
float rms_3=0;
float rms ;
char str1[6];
char str2[6];
char str3[6];
/*<<<<<<<<<<<<<<<<currentsensorparameter>>>>>>>>>>>>>*/
void setup()
{
Serial.begin(9600);
printf_begin();
//Setup and configure rf radio
radio.begin();
radio.setDataRate(RF24_1MBPS); // rate 1MBPS
radio.setPALevel(RF24_PA_MAX);
radio.setChannel(70); // channel 50
// delay 1ms, 3 retries
// 0 - 250us, 15 - 4000us
//radio.setRetries(15,15);
radio.openWritingPipe(pipes[0]); //seding address
radio.openReadingPipe(1,pipes[1]); //receiving address
radio.startListening(); // listening to catch packets
radio.printDetails();
}
void loop()
{
currentsensor_ACS712_A0();
currentsensor_ACS712_A1();
currentsensor_ACS712_A2();

77
header('1',

'0',

'3');//(message[0]=source,

'1',

'2',

message[1]=receiver,

essage[4]=sensorno)
message_send();

message_receive();
return setup();
}
//header function
void

header(char

source,

char

receiver,

char

sensorno1,char sensorno2,char sensorno3 )


{
/*Max nRF payload size = 32 bytes
header:1st byte : source address
2nd byte : receiver address
3rd byte : packet seqeunce number
4th byte : switch number
5th byte : unused
6th byte : hop sequence number*/
message[0] = source; //Node 1 address = 1
message[1] = receiver; //Access Point source = 0
message[2] = '1'; //Packet sequence = 1
message[4] = sensorno1;
message[5] = '1'; //hop sequence = 1
message[6] = sensorno2;
message[7] = sensorno3;
}
//<<<<<<<<<<<<<<<message_print function>>>>>>>>>>>>>>>

78
int message_print(float data1, float data2, float data3
,char*

sensorStatus)

//data

use

str

receive and switch_on_off=switch on/off


{
Serial.print("\n| source = ");
Serial.println(message[0]);
Serial.print("| receiver = ");
Serial.println(message[1]);
Serial.print("| packet sequence = ");
Serial.println(message[2]);
Serial.print("| current sensor = ");
Serial.println(message[4]);
Serial.print("| current sensor = ");
Serial.println(message[6]);
Serial.print("| current sensor = ");
Serial.println(message[7]);
Serial.print("| hope sequence = ");
Serial.println(message[5]);
Serial.print("| message size = ");
Serial.println(sizeof(message));
Serial.print("| data1 = ");
Serial.println(data1);
Serial.print("| data2 = ");
Serial.println(data2);
Serial.print("| data3 = ");
Serial.println(data3);
Serial.print("| message size = ");
Serial.println(sensorStatus);
Serial.print("| str1 size = ");
Serial.println(sizeof(str1));
Serial.print("| str2 size = ");
Serial.println(sizeof(str2));
Serial.print("| str3 size = ");
Serial.println(sizeof(str3));
//Serial.print("| data size = ");
//Serial.print(sizeof(atof(str)));
}

send/atoi(str)

79

//<<<<<<<<<<<<<<<<Message_receive
function>>>>>>>>>>>>>>>>>
void message_receive()
{
if ( radio.available() )
{
radio.read( &message, sizeof(message) );
int j=0;
for(int i=8; i <= 7+ds; i++)
{
str1[j] = message[i];
j=j+1;
}
j=0;
for(int i=15; i <= 14+ds; i++)
{
str2[j] = message[i];
j=j+1;
}
j=0;
for(int i=22; i <= 21+ds; i++)
{
str3[j] = message[i];
j=j+1;
}
if (message[1] == '1')
{
if

(message[4]

==

||message[7] == '3')
{
rms_1 = atof(str1);

'1'

||message[6]

==

'2'

80
rms_2 = atof(str2);
rms_3 = atof(str3);
message_print( rms_1 ,rms_2 ,rms_3 ," (Current
sensor_A0 sensor_A1 sensor_A2

data send) ");

}
}
if(message[1]!='1'&&message[5]=='1')
{
message[5]='2';
if

(message[4]

==

'1'

||message[6]

==

'2'

||message[7] == '3')
{
rms_1 = atof(str1);
message_print( rms_1 ,rms_2 ,rms_3 ," (Current
sensor_A0 sensor_A1 sensor_A2

data send) ");

Serial.print("\n not my address resend ");


delay(500);
radio.stopListening();
radio.write( &message, sizeof(message) );
radio.startListening();
}
}
else if(message[1]!='1'&&message[5]=='2')
{
if

(message[4]

==

'1'

||message[6]

==

'2'

||message[7] == '3')
{
rms_1 = atof(str1);
message_print( rms_1 ,rms_2 ,rms_3 ," (Current
sensor_A0 sensor_A1 sensor_A2

data send) ");

Serial.print("\n messeage deleted ");


delay(500);
}
}

81
}
}
//<<<<<<<<<<<<<<<message_send function>>>>>>>>>>>>>>>
void message_send()
{
dtostrf(rms_1, 4, 2, str1);
//itoa(rms,

str,

10);

//integer

to

string

itoa(int

val, string array, base)


int j=0;
for(int i=8; i <= 7+ds; i++)
{
message[i]=str1[j];
j=j+1;
}
dtostrf(rms_2, 4, 2, str2);
j=0;
for(int i=15; i <= 14+ds; i++)
{
message[i]=str2[j];
j=j+1;
}
dtostrf(rms_3, 4, 2, str3);
j=0;
for(int i=22; i <= 21+ds; i++)
{
message[i]=str3[j];
j=j+1;
}
if (message[4] == '1' ||message[6] == '2' ||message[7]
== '3')
{
message_print(

rms_1

,rms_2

sensor_A0 sensor_A1 sensor_A2

,rms_3

,"

data send) ");

(Current

82
}
radio.stopListening();
radio.write( &message, sizeof(message) );
radio.startListening();
}
//<<<<<<<<<<<<<<<<<print.h file>>>>>>>>>>>>>>>>>>>>
/*
Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>
This program is free software; you can redistribute it
and/or
modify it under the terms of the GNU General Public
License
version 2 as published by the Free Software Foundation.
*/
/**
* @file printf.h
*
*

Setup

necessary

to

direct

Serial library, which


* enables 'printf'
*/
#ifndef __PRINTF_H__
#define __PRINTF_H__
#ifdef ARDUINO
int serial_putc( char c, FILE * )
{
Serial.write( c );
return c;
}

stdout

to

the

Arduino

83

void printf_begin(void)
{
fdevopen( &serial_putc, 0 );
}
#else
#error This example is only for use on Arduino.
#endif // ARDUINO
#endif // __PRINTF_H__
//<<<<<<<<<<<<<currentsensor_ACS712_A0function>>>>>>>>>
void currentsensor_ACS712_A0()
{
if (z_A0 == 0)
{
for (int i=0; i<5000; i++)
{
adc_zero_A0 += analogRead (currentPin_A0);
//adc_zero += adc_zeroread;
}
adc_zero_A0 /= 5000;
z_A0 = z_A0 + 1 ;
}
if (x_A0 == 0)
{
initialize_csensor_A0() ;
}

unsigned long currentAcc_A0 = 0;


unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)

84
{
if (micros() - prevMicros >= sampleInterval)
{
sensorValue_A0 = analogRead (currentPin_A0);
adc_raw_A0 = sensorValue_A0 - adc_zero_A0;
currentAcc_A0

+=

(unsigned

long)(adc_raw_A0

adc_raw_A0);
++count;
prevMicros += sampleInterval;
}
}
for (int i=0; i<3000; i++)
{
rms_A0

+=

sqrt((float)currentAcc_A0/(float)numSamples)

(75.7576

/ 1023.0);
}
rms_A0 /= 3000;
rms_1 = rms_A0 - rms_i_A0 ;
Serial.print(" sensorValue_A0 = ");
Serial.println(sensorValue_A0);
Serial.print(" adc_raw_A0= ");
Serial.println(adc_raw_A0);
Serial.print(" adc_zero A0 = ");
Serial.println(adc_zero_A0);
delay (500);
}
//

<<<<<<<<<<<<<currentsensor_ACS712_A1

function>>>>>>>>>>>>>>
void currentsensor_ACS712_A1()
{
if (z_A1 == 0)
{
for (int i=0; i<5000; i++)

85
{
adc_zero_A1 += analogRead (currentPin_A1);
//adc_zero += adc_zeroread;
}
adc_zero_A1 /= 5000;
z_A1 = z_A1 + 1 ;
}
if (x_A1 == 0)
{
initialize_csensor_A1() ;
}

unsigned long currentAcc_A1 = 0;


unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)
{
if (micros() - prevMicros >= sampleInterval)
{
sensorValue_A1 = analogRead (currentPin_A1);
adc_raw_A1 = sensorValue_A1 - adc_zero_A1;
currentAcc_A1

+=

(unsigned

long)(adc_raw_A1

adc_raw_A1);
++count;
prevMicros += sampleInterval;
}
}
for (int i=0; i<3000; i++)
{
rms_A1
sqrt((float)currentAcc_A1/(float)numSamples)
/ 1023.0);
}
rms_A1 /= 3000;

+=
*

(75.7576

86
rms_2 = rms_A1 - rms_i_A1 ;
Serial.print(" sensorValue_A1 = ");
Serial.println(sensorValue_A1);
Serial.print(" adc_raw_A1= ");
Serial.println(adc_raw_A1);
Serial.print(" adc_zero A1 = ");
Serial.println(adc_zero_A1);
delay (500);
}

//<<<<<<<currentsensor_ACS712_A2 function>>>>>>>>>>>>>
void currentsensor_ACS712_A2()
{
if (z_A2 == 0)
{
for (int i=0; i<5000; i++)
{
adc_zero_A2 += analogRead (currentPin_A2);
//adc_zero += adc_zeroread;
}
adc_zero_A2 /= 5000;
z_A2 = z_A2 + 1 ;
}
if (x_A2 == 0)
{
initialize_csensor_A2() ;
}
unsigned long currentAcc_A2 = 0;
unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)
{
if (micros() - prevMicros >= sampleInterval)
{
sensorValue_A2 = analogRead (currentPin_A2);

87
adc_raw_A2 = sensorValue_A2 - adc_zero_A2;
currentAcc_A2 += (unsigned long)(adc_raw_A2
* adc_raw_A2);
++count;
prevMicros += sampleInterval;
}
}
for (int i=0; i<3000; i++)
{
rms_A2
sqrt((float)currentAcc_A2/(float)numSamples)

+=
*

(75.7576

/ 1023.0);
}
rms_A2 /= 3000;
rms_3 = rms_A2 - rms_i_A2 ;
Serial.print(" sensorValue_A2 = ");
Serial.println(sensorValue_A2);
Serial.print(" adc_raw_A2= ");
Serial.println(adc_raw_A2);
Serial.print(" adc_zero A2 = ");
Serial.println(adc_zero_A2);
delay (500);
}
//<<<<<<<<<<<<initialize_csensor_A0 function>>>>>>>>>>>>
void initialize_csensor_A0()
{
unsigned long currentAcc_A0 = 0;
unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)
{
if (micros() - prevMicros >= sampleInterval)
{
sensorValue_A0 = analogRead (currentPin_A0);

88
adc_raw_A0 = sensorValue_A0 - adc_zero_A0;
currentAcc_A0

+=

(unsigned

long)(adc_raw_A0

adc_raw_A0);
++count;
prevMicros += sampleInterval;
}
}
for (int i=0; i<5000; i++)
{
rms_i_A0

+=

sqrt((float)currentAcc_A0/(float)numSamples)

(75.7576

/ 1023.0);
}
rms_i_A0 /= 5000;
Serial.print(" current initialize A0= ");
Serial.println(rms_i_A0);
x_A0 = x_A0 + 1;
}
//<<<<<<<<<initialize_csensor_A1 function>>>>>>>>>>>
void initialize_csensor_A1()
{
unsigned long currentAcc_A1 = 0;
unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)
{
if (micros() - prevMicros >= sampleInterval)
{
sensorValue_A1 = analogRead (currentPin_A1);
adc_raw_A1 = sensorValue_A1 - adc_zero_A1;
currentAcc_A1

+=

(unsigned

adc_raw_A1);
++count;
prevMicros += sampleInterval;

long)(adc_raw_A1

89
}
}
for (int i=0; i<5000; i++)
{
rms_i_A1

+=

sqrt((float)currentAcc_A1/(float)numSamples)

(75.7576

/ 1023.0);
}
rms_i_A1 /= 5000;
Serial.print(" current initialize A1 = ");
Serial.println(rms_i_A1);
x_A1 = x_A1 + 1;
}
//<<<<<<<<<<initialize_csensor_A2 function>>>>>>>>>>>>>>
void initialize_csensor_A2()
{
unsigned long currentAcc_A2 = 0;
unsigned int count = 0;
unsigned long prevMicros = micros() - sampleInterval ;
while (count < numSamples)
{
if (micros() - prevMicros >= sampleInterval)
{
sensorValue_A2 = analogRead (currentPin_A2);
adc_raw_A2 = sensorValue_A2 - adc_zero_A2;
currentAcc_A2

+=

(unsigned

adc_raw_A2);
++count;
prevMicros += sampleInterval;
}
}
for (int i=0; i<5000; i++)
{

long)(adc_raw_A2

90
rms_i_A2
sqrt((float)currentAcc_A2/(float)numSamples)
/ 1023.0);
}
rms_i_A2 /= 5000;
Serial.print(" current initialize A2= ");
Serial.println(rms_i_A2);
x_A2 = x_A2 + 1;

+=
*

(75.7576

91
APPENDIX B

Raspberry Pi (AP) soft code

/* - CONNECTIONS: nRF24L01 Modules See:


http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
1 - GND
2 - VCC 3.3V !!! NOT 5V
3 - CE to Arduino pin 9
4 - CSN to Arduino pin 10
5 - SCK to Arduino pin 13
6 - MOSI to Arduino pin 11
7 - MISO to Arduino pin 12
8 - UNUSED */
/*-----( Import needed libraries )-----*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <cstring>
#include <getopt.h>
#include <cstdlib>
#include <iostream>
#include <ctype.h>
#include "../RF24.h"
#include <math.h>
#include <stdarg.h>
/*-----( Connecting to mysql )-----*/
//#include <my_global.h> // Include this file first to avoid
problems
#include <mysql/mysql.h> // MySQL Include File
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "admin"
#define DATABASE "smarhome"
//#include <unistd.h>

using namespace std;


RF24 radio("/dev/spidev0.0",8000000 , 25); //spi device,
speed and CSN,only CSN is NEEDED in RPI
const int role_pin = 7;
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
char message[32]; // message payload 32byte 0-31

92

int ds = 7; //datasize
float rms;
float rms_1=0;
float rms_2=0;
float rms_3=0;
char str1[6];
char str2[6];
char str3[6];
char *pEnd;
float power_1 = 0;
float power_2 = 0;
float power_3 = 0;
float power_6=0.04;
float rm_A0 = 0;
float rm_A1 = 0;
float rm_A2 = 0;
float rm_total = 0;
float rm_1 = 0;
float rm_2 = 0;
float rm_3 = 0;
float rm_4 = 0;
float rm_5 = 0;
float power_Acc_A1;
float power_Acc_A2;
float power_Acc_A3;
float power_Acc_A4;
float power_Acc_B1;
float power_Acc_B2;
float power_Acc_B3;
float power_Acc_B4;
float power_Acc_C1;
float power_Acc_C2;
float power_Acc_C3;
float power_Acc_C4;

void setup(void)
{
//Prepare the radio module
printf("\nPreparing interface\n");
radio.begin();
radio.setRetries( 15, 15);
radio.setChannel(0x46);
radio.setPALevel(RF24_PA_MAX);
radio.setPALevel(RF24_PA_MAX);
radio.openWritingPipe(pipes[0]);
radio.openReadingPipe(1,pipes[1]);
radio.startListening();
radio.printDetails();
}

93

void power_A0()
/*power calculation for current sensor A0*/
{
if (rms_1 > 0.00)
{
power_1 = (((sqrt(rms_1*rms_1) * 240)/1000) + power_1) ;
}
/*convert power to tnb tariff in Ringgit Malaysia*/
if (power_1 <= 720000)
{
rm_1 = (power_1 * 0.000060555);
rm_A0 = rm_1;
}
if (power_1 > 720000)
{
float power_Acc_A1 = power_1 - 720000 ;
rm_2 = power_Acc_A1 * 0.000092777;
rm_A0 = rm_1 + rm_2 ;
}
if (power_1 > 1080000)
{
float power_Acc_A2 = power_1 - 1080000 ;
rm_3 = (power_Acc_A2 * 0.000143333);
rm_A0 = rm_1 + rm_2 +rm_3 ;
}
if (power_1 > 2160000)
{
float power_Acc_A3 = power_1 - 2160000;
rm_4 = power_Acc_A3 * 0.000546;
rm_A0 = rm_1 + rm_2 +rm_3 + rm_4 ;
}
if (power_1 > 3240000)
{
float power_Acc_A4 = power_1 -3240000;
rm_5 = power_Acc_A4 * 0.000151666;
rm_A0 = rm_1 + rm_2 +rm_3 + rm_4 + rm_5;
}
printf("\n power_1 = %f", (power_1));
printf("\n RM = %f", (rm_A0));
}
void power_A1 ()
{
/*power calculation for current sensor A1*/
if (rms_2 > 0.00)
{
power_2 = ((sqrt(rms_2*rms_2) * 240)/1000) + power_2 ;
}
/*convert power to tnb tariff in Ringgit Malaysia*/
if (power_2 <= 720000)
{
rm_1 = (power_2 * 0.000060555);

94
rm_A1 = rm_1;
}
if (power_2 > 720000)
{
float power_Acc_B1 = power_2 - 720000 ;
rm_2 = power_Acc_B1 * 0.000092777;
rm_A1 = rm_1 + rm_2 ;
}
if (power_2 > 1080000)
{
float power_Acc_B2 = power_2 - 1080000 ;
rm_3 = (power_Acc_B2 * 0.000143333);
rm_A1 = rm_1 + rm_2 +rm_3;
}
if (power_2 > 2160000)
{
float power_Acc_B3 = power_2 - 2160000;
rm_4 = power_Acc_B3 * 0.000546;
rm_A1 = rm_1 + rm_2 +rm_3 + rm_4 ;
}
if (power_2 > 3240000)
{
float power_Acc_B4 = power_2 -3240000;
rm_5 = power_Acc_B4 * 0.000151666;
rm_A1 = rm_1 + rm_2 +rm_3 + rm_4 + rm_5;
}
printf("\n power_2 = %f", (power_2));
printf("\n RM = %f", (rm_A1));
}
void power_A2 ()
{
/*power calculation for current sensor A2*/
if (rms_3 > 0.00)
{
power_3 = ((sqrt(rms_3*rms_3) * 240)/1000) + power_3 ;
}
/*convert power to tnb tariff in Ringgit Malaysia*/
if (power_3 <= 720000)
{
rm_1 = (power_3 * 0.000060555);
rm_A2 = rm_1 ;
}
if (power_3 > 720000)
{
float power_Acc_C1 = power_3 - 720000 ;
rm_2 = power_Acc_C1 * 0.000092777;
rm_A2 = rm_1 + rm_2 ;
}
if (power_3 > 1080000)
{
float power_Acc_C2 = power_3 - 1080000 ;
rm_3 = (power_Acc_C2 * 0.000143333);

95
rm_A2 = rm_1 + rm_2 +rm_3 ;
}
if (power_3 > 2160000)
{
float power_Acc_C3 = power_3 - 2160000;
rm_4 = power_Acc_C3 * 0.000546;
rm_A2 = rm_1 + rm_2 +rm_3 + rm_4 ;
}
if (power_3 > 3240000)
{
float power_Acc_C4 = power_3 -3240000;
rm_5 = power_Acc_C4 * 0.000151666;
rm_A2 = rm_1 + rm_2 +rm_3 + rm_4 + rm_5;
}
printf("\n power_3 = %f",(power_3));
printf("\n RM = %f", (rm_A2));
}
void header(char source, char receiver,
sensorno2, char sensorno3 )
{
/*Max nRF payload size = 32 bytes
header:1st byte : source address
2nd byte : receiver address
3rd byte : packet seqeunce number
4th byte : switch number
5th byte : unused
6th byte : hop sequence number*/
message[0] = source; //Node 1 address
message[1] = receiver; //Access Point
message[2] = '1'; //Packet sequence =
message[4]
message[5]
message[6]
message[7]

=
=
=
=

char sensorno1, char

= 1
source = 0
1

sensorno1 ;
'1'; //hop sequence = 1
sensorno2 ;
sensorno3 ;

}
void message_printsensor(float data1, float data2, float data3
,const char* sensorStatus) //data use str send/atoi(str)
receive and switch_on_off=switch on/off
{
string sensorstatusprint = sensorStatus;
printf("\n| source = %c ", message[0]);
printf("\n| receiver = %c ",message[1]);
printf("\n| packet sequence = %c",message[2]);
printf("\n| current sensor = %c" ,message[4]);
printf("\n| current sensor = %c", message[6]);

96
printf("\n| current sensor = %c", message[7]);
printf("\n| hope sequence = %c ", message[5]);
printf("\n| message size = %d", sizeof(message));
printf("\n| data1 = %f",(data1));
printf("\n| data2 = %f", (data2));
printf("\n| data3 = %f", (data3));
printf("\n| %s", sensorstatusprint.c_str());
printf("\n| str1 size = %d",(sizeof(str1)));
printf("\n| str2 size = %d", (sizeof(str2)));
printf("\n| str3 size = %d", (sizeof(str3)));
printf("\n| atof str1 size = %d", (sizeof(atof(str1))));
printf("\n| atof str2 size = %d",(sizeof(atof(str2))));
printf("\n| atof str3 size = %d", (sizeof(atof(str3))));
}
void message_receive()
{
if ( radio.available() )
{
MYSQL *connect; // Create a pointer to the MySQL instance
connect=mysql_init(NULL); // Initialise the instance
connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABA
SE,0,NULL,0);
radio.read( &message, sizeof(message) );
int j=0;
for(int i=8; i <= 7+ds; i++)
{
str1[j] = message[i];
j=j+1;
}
j=0;
for(int i=15; i <= 14+ds; i++)
{
str2[j] = message[i];
j=j+1;
}

97
j=0;
for(int i=22; i <= 21+ds; i++)
{
str3[j] = message[i];
j=j+1;
}
if (message[1] == '0')
{
if (message[4] == '1' ||message[6] == '2' ||message[7]
== '3')
{
rms_1 = strtof(str1,&pEnd);
rms_2 = strtof(str2,&pEnd);
rms_3 = strtof(str3,&pEnd);
power_A0();
power_A1();
power_A2();
rm_total = rm_A0 + rm_A1 + rm_A2 ;
message_printsensor( rms_1 ,rms_2 ,rms_3 ," (Current sensor_A0
sensor_A1 sensor_A2 data receive) ");
/*MYSQL *connect; // Create a pointer to the MySQL instance
connect=mysql_init(NULL); // Initialise the instance
connect=mysql_real_connect
(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0);*/
char query[700]={0};
//if(rms_1<=0.000001 || rms_2<=0.000001 || rms_3<=0.000001)
//{
// rms_1=0;
// rms_2=0;
// rms_3=0;
//}

memset(query,0,sizeof(query));
sprintf(query, "INSERT INTO
powermonitor(powerconsume1,powerconsume2,powerconsume3,
currentconsume1,currentconsume2,currentconsume3,
costrm1,costrm2,costrm3,totalcostrm,time ) VALUE
(%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,NOW())",power_1,power_2,power_3
,rms_1,rms_2,rms_3,rm_A0,rm_A1,rm_A2,rm_total);
mysql_query(connect,query);
memset(query,0,sizeof(query));

98
sprintf(query, "UPDATE smarhome.powermonitortotal SET
powerconsume1=%f,powerconsume2=%f,powerconsume3=%f,currentcons
ume1=%f,currentconsume2=%f,currentconsume3=%f,costrm1=%f,costr
m2=%f,costrm3=%f,totalcostrm=%f, time=NOW() WHERE
powermonitortotal.power_id='1'",power_1,power_2,power_3,rms_1,
rms_2,rms_3,rm_A0,rm_A1,rm_A2,rm_total);
mysql_query(connect,query);

mysql_close(connect);
}

}
if(message[1]!='0'&&message[5]=='1')
{
message[5]='2';
if (message[4] == '1' ||message[6] == '2' ||message[7]
== '3')
{
rms_1 = strtof(str1,&pEnd);
rms_2 = strtof(str2,&pEnd);
rms_3 = strtof(str3,&pEnd);
message_printsensor( rms_1 ,rms_2 ,rms_3 ," (Current
sensor_A0 sensor_A1 sensor_A2 data send) ");
printf("\n not my address resend ");
usleep (500);
radio.stopListening();
radio.write( &message, sizeof(message) );
radio.startListening();
}
}
else if(message[1]!='0'&&message[5]=='2')
{
if (message[4] == '1' ||message[6] == '2' ||message[7]
== '3')
{
rms_1 = strtof(str1,&pEnd);
message_printsensor( rms_1 ,rms_2 ,rms_3 ," (Current
sensor_A0
sensor_A1 sensor_A2 data send) ");
printf("\n messeage deleted ");
//usleep (500);
}
}
}
}

99

void loop()
{
message_receive();
rm_total = rm_A0 + rm_A1 + rm_A2 ;
usleep (100000);
}
void loop2()
{
//usleep(500000);
MYSQL *connect; // Create a pointer to the MySQL instance
connect=mysql_init(NULL); // Initialise the instance
if(!connect)
{
fprintf(stderr,"MySQL Initialization Failed");
}
connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABA
SE,0,NULL,0);
if(connect)
{
//printf("\nConnection Succeeded");
}
else
{
printf("\nConnection Failed!");
}
MYSQL_RES *res_set;
MYSQL_ROW row;
mysql_query(connect,"SELECT power_id, powerconsume FROM
powermonitor WHERE powermonitor.power_id = '1'");
res_set = mysql_store_result(connect);
while ((row = mysql_fetch_row(res_set)) != NULL)
{
printf("\npower_id = %s\npowerconsume= %s\n", row[0],
row[1]);
//power_1 = row[1];
}
mysql_free_result(res_set);
mysql_close(connect);
/* Close and shutdown */
usleep(200000);

100
//return loop();
}

int main(int argc, char** argv)


{
setup();
while (1)
loop();
}

101
APPENDIX C

Setting up a Web server using Raspian wheezy on the Raspberry Pi

Setting up a Web Server using Raspbian Wheezy on the Raspberry Pi ( Kenneth A


Spencer)

To use the Raspbian Wheezy distribution of the Debian Linux release of Wheezy,
for the Raspberry Pi, as a web server requires changes to the basic configuration and
the installation of additional software. It is also advised that once these processes
have been carried out, a full backup copy of the host SD Card should be made for
easy restoration, and this topic is also discussed.

This document explains fully how to make your Raspberry Pi ready to function as a
Web Server with database and PHP programming support. It is in three parts. Part A
deals with obtaining, installing and configuring the software which you will need,
and ensuring that it is all working. Part B discusses backup methods. Part C explains
and illustrates some ways of making valuable use out of the machine and the
software which has been installed.

Part A: Obtaining, Installing and Configuring the Software

A1. Install RaspbianWheezy The 20121018 distribution of RaspbianWheezy can be


installed using Win32DiskImager.exe having copied an image of the distribution
image into the same location as the executable. New images are available from time
to time from www.raspberrypi.org/downloads.

A2. Boot the Image This distribution is the first to have the Raspbi-Config program,
which starts on first boot. Ensure that the keyboard type, keyboard layout, keyboard
language, locale and time zone are correctly selected. Then ensure that ssh is
configured for startup, so as to allow remote login when required, and that the option

102
is selected for expansion of the root filing system to occupy the full capacity of the
SD Card. The configuration program also offers a range of over-clocking options
from a conservative increase of CPU frequency by 100MHz to a maximum of
300MHz combined with CPU voltage and RAM frequency increases. Note that the
root filing system will be expanded at the next boot, and that this process will take an
hour at least, although it will vary with your SD Card size. There is no indication of
progress, so just wait!

A3. Set a root password Once the machine is rebooted after stage A2, execute the
command: sudo passwd and enter your preferred root password. As the installations
and reconfigurations are best carried out with root privilege you should then issue
the command: sudo su which is the easiest way to change to the privilege level
required for the rest of your session.

A4. Install the proftpd ftp server Execute the following command to obtain and
install the proftpd ftp sever: apt-get install proftpd You will use proftpd later on to
transfer your website files to the newly configured web server. Once proftpd is
installed, it is easier to continue with the configuration by remote login at a PC or
Mac workstation. Use an ssh terminal client such as PuTTy which is readily
available free-of-charge. Download and install it onto your PC. Then run it and enter
the IP address of your Raspberry Pi so as to login. To get the IP address, execute the
command ifconfig directly at the Raspberry Pi (see A5.1). Once logged in remotely
with PuTTy, you will be able to update the RaspbianWheezy installed components,
install the Apache2 web server, install the PHP5 programming environment, install
the MySQL database, install APC support for PHP, and finally install the nmap
utilities. Collectively these components constitute the so-called LAMP server and
their installation is described in the succeeding sections 5 to 9 below.

A5. Install the Apache2 web server If you wish, you can copy and paste the
commands from the following paragraphs by highlighting the text of each command,
tapping [Ctrl]+C (to copy the highlighted text), and then right-clicking over the
cursor in the PuTTy window. Before installing any more software packages, update
your system fully by executing the following: sudo apt-get update && sudo apt-get

103
upgrade Then execute the following command to obtain and install the Apache2 web
server: apt-get install apache2 Apache2 will be running after installation, but if you
need to start or stop it, the commands are: service apache2 start

service apache2

stop A5.1 After the initial installation, Apache2 may report the following warning
when started or stopped: Could not determine the server's fully qualified domain
name, using 127.0.X.1 for ServerName This means that Apache2 is not quite
correctly configured for your individual Raspberry Pi. To resolve this, first identify
and note down the IP address of your Raspberry Pi machine (also explained in 4.
above): ifconfig Record the numbers immediately following inet addr: in the first
paragraph of the output. Then, edit two existing files, and create an new file as
detailed in A5.1a below.

A5.1a Edit /etc/hostname as follows: cd /etc nano hostname nano is a Linux editor.
Change the line raspberrypi to your chosen name for your server.

Mine is

raspbianwheezy97. This is essential anyway if you have more than one Raspberry Pi.
Then save the file with [Ctrl]+O and exit nano with [Ctrl]+X.

A5.1b Then edit /etc/hosts as follows: nano hosts Add the lines (the first line may
already present but commented out with a # symbol): 127.0.0.1 localhost 10.0.0.97
localhost and, if you wish, also add the following line to the hosts file: 10.0.0.97
raspbianwheezy97 In the /etc/hosts file, 127.0.0.1 is the standard IP address and
localhost the standard TC/IP hostname for local reference to the current physical
machine. Replace 10.0.0.97 by your actual IP address noted earlier, and
raspbianwheezy97 by your chosen name for your Raspberry Pi machine. Then save
the file with [Ctrl]+O and exit nano with [Ctrl]+X.

A5.1c Next, create an extra file in the /etc/apache2/conf.d directory as follows: cd


/etc/apache2/conf.d nano servername.conf which will open the nano editor with a
new empty file called servername.conf. Type your ServerName into the file under
the ServerName directive: ServerName raspbianwheezy97 Change the name to that
chosen for your own machine. Then save the file [Ctrl]+O and exit nano with
[Ctrl]+X. As Apache2 loads data from the files in conf.d into its configuration, these
changes will remove the error concerning Apache2 not finding your server name. It

104
is preferable to use this method of adding to the Apache2 configuration as editing the
main configuration file may introduce unintentional errors. Stop and start Apache2
as described in A5. above.

A5.2 After restarting Apache2 you can test Apache2 from your remote workstation
by typing http://10.0.0.97 into the address bar of a web browser (e.g. Internet
Explorer). Replace 10.0.0.97 with your own Raspberry Pi's IP address. You should
see a message stating "It works!"

If you wish to be able to type http://raspbianwheezy97 into the address bar, then you
must add 10.0.0.97 raspbianwheezy97 into your Windows hosts file, which is
commonly in C:\Windows\System32\drivers\etc. By now you know that you must
use your own Raspberry Pi IP address and chosen hostname. If you have a Domain
Name Server (DNS) on your network, it is preferable to record the Raspberry Pi's
details in that rather than in the hosts files of all of your workstations.

A6. Install the PHP programming environment PHP is a very useful server-side
programming or scripting language which amongst many other things allows your
web pages to use the MySQL database management system to load data into your
pages, and to save data from your pages into your database.

Execute the following command to obtain and install the PHP programming
environment version 5: apt-get install php5 libapache2-mod-php5 php5-intl php5mcrypt php5-curl php5-gd php5-sqlite [NB: all on a single line]

If you wish, you can create a simple web page to show the PHP configuration
information: cd /var/www to get to the directory containing your web page. Then
open nano with an empty file: nano phpinformation.php When it opens, type in the
following: <?php phpinfo(); ?> Then save the file with [Ctrl]+O and exit nano with
[Ctrl]+X.

View

your

new

page

by

typing

http://raspbianwheezy97/phpinformation.php into your browser address bar,


remembering to substitute your Raspberry Pi's IP address or host/server name for
mine.

105
A7. Install the MySQL database management system Execute the following
command to obtain and install the MySQL database management system: apt-get
install mysql-server mysql-client php5-mysql During the installation, you will be
invited to enter a password for the top level MySQL user. The username is
commonly root, but the password is up to you. Note that this is the managing user
for MySQL and is not related to the root user of your Raspbian Wheezy operating
system.

Then to take account of system and configuration changes, stop and start the
Apache2 web server.

You can test your MySQL installation by logging in to MySQL. You will have to
use the MySQL root user for the moment: mysql -u root -p The -u parameter
signifies that the next item is a username, and the -p parameter tells MySQL to
expect a password. When prompted, enter the root password created earlier, and
MySQL will respond with an Oracle copyright notice and the mysql> prompt. Exit
MySQL by typing exit.

It is very much easier to manage a database, including the creation of tables and
other database objects in MySQL using phpMyAdmin, and we will install that most
useful tool very shortly. But we have two or three more steps to complete first.

A8. Install the APC support package for PHP ACP is an alternative caching support
system for PHP, which enables PHP intermediate code to be cached. This can
improve the performance of Apache2 and other programs which may execute PHP
code. Execute the following command to obtain and install the APC support system
for PHP: apt-get install php-pear php5-dev apache2-prefork-dev build- essential
make && pecl install apc [NB: all on a single line] Then edit the php.ini
configuration file: nano /etc/php5/apache2/php.ini and add the following text to the
file, in the Dynamic Extension section, some way down the file: extension=apc.so
Then to take account of system and configuration changes, stop and start the
Apache2 web server.

106
A9. Install some additional items There are a few additional items which may be
usefully installed before we install the next major item. Execute the following
command to obtain and install them: apt-get install nmap It installs some additional
fonts, the nmap network analysis tool some other utilities. The nmap program has a
GUI interface, (on your Pi only) called zenmap which can be installed by: apt-get
install zenmap.

A10. Install phpMyAdmin phpMyAdmin is one of the most useful tools for working
with the MySQL database management system. It is a web-based control panel, but
it is not only that. It also includes support for creating and amending your database
tables, for entering data into them, and for designing and executing queries. Execute
the following command to obtain and install phpMyAdmin:

apt-get install

libapache2-mod-auth-mysql php5-mysql phpmyadmin When asked if phpMyAdmin


should configure a MySQL database for itself, select yes. When asked, enter the
password of the root MySQL user, so as to authenticate yourself on MySQL. Once
authenticated on MySQL you will be asked to create and confirm a password for
phpMyAdmin. Then youll be asked which server on which to install it: select
Apache2. During the installation, you will be offered several options: accept the
default suggestions at this stage of your knowledge! After further processing, the
phpMyAdmin installation will finish.

There are two adjustments to the

configurations necessary before you can use phpMyAdmin. First edit the php.ini file
to include a MySQL library:

nano /etc/php5/apache2/php.ini Then type the

following text into the Dynamic Extensions section about two thirds down the page:
Shellextension=mysql.so As things stand, there is no provision for showing the
phpMyAdmin pages from your default web page directory. To such an create an
entry make a symbolic link in the Apache2 data directory, as follows: cd /var/www
ln -s /usr/share/phpmyadmin Now from a workstation, youll be able to navigate to:
http://raspbianwheezy97/phpmyadmin

or

directly

on

your

Pi

to:

http://localhost/phpmyadmin If logging in from a workstation, remember to


substitute your own IP address or if you have entered it into your DNS server or the
workstation's hosts file, you may enter your hostname.

107
When invited to login on the phpMyAdmin opening page, respond with the
username root and the password which you created during phpMyAdmin
installation.

A11. Install the Webmin administration Tool Webmin is an extremely useful tool for
administering all aspects of a Linux server.

Before installing Webmin, it is necessary to edit the sources.list file:


/etc/apt/sources.list

Add

the

following

http://download.webmin.com/download/repository

two
sarge

nano

lines:

deb

contrib

deb

http://webmin.mirror.somersettechsolutions.co.uk/repository sarge contrib [NB: the


second entry must be all on a single line]

Then you must obtain and install the GPG key with which the repository holding
Webmin is signed: cd /root wget http://www.webmin.com/jcameron-key.asc aptkey add jcameron-key.asc

Then get any system updates, following which you can obtain and install the
Webmin package(s): apt-get update apt-get install webmin It may take some time,
but all dependencies should be resolved automatically.

Webmin runs it's own secure sockets web server, separate from Apache2. It does this
using its own port number (10000) which must be added to the Webmin address
when typed into your web browser address bar: https://10.0.0.97:10000/. The https://
in the address bar indicates that the web browser is asking for the page using secure
sockets layer, which is a more secure protocol than the usual http://. Of course, you
can also use the form https://yourPiHostname:10000 for the Webmin address if you
wish and if you have your Pi details in the workstation hosts file or in a DNS server..
When invited to login, you will normally respond as user root with your root
password, or as any user who can use sudo to run commands as root.

A12. Install the Webalizer Graphical Webstats package By default, the Apache2 web
server generates a line of data in a log file for each request it receives to serve a

108
webpage. This data consists of a series of fields containing such items as the IP
address of the client requesting the page, the date and time, the filename of the page,
the browser and operating system, and more. You can read this data into a database
for analysis, but it can also be converted into a graphical display which is useful for
less formal study of the use of your web server activity.

You can obtain and install Webalizer by executing the following command: apt-get
install webalizer The default configuration of Webalizer is not quite correct for
Apache2 under Raspbian Wheezy. Therefore you must edit the Webalizer
configuration file /etc/webalizer/webalizer.conf nano /etc/webalizer/webalizer.conf
In the webalizer.conf file, for the setup of Apache2 so far, you may need to locate
and edit the Apache2 log file entry to: logfile /var/log/apache2/access.log Later, if
you decide to implement multiple virtual hosts on Apache2 this entry will need
further amendment. In addition, it appears that Webalizer does not install the default
geographical IP locator database, but instead installs GeoIP. Therefore edit the
webalizer.conf file further: Uncomment/edit the lines: GeoIP yes GeoIPDatabase
/usr/share/GeoIP/GeoIP.dat

Part B: Backup your installation

Now that you have installed and tested the Debian variant of Linux known as
Rasbian Wheezy, the ftp server proftpd, the Apache2 web sever, the PHP
programming environment and its support system APC, the MySQL database
management system, phpMyAdmin MySQL management tool, and the Webmin
general server management tool, you would be well-advised to make a backup of the
SD Card.

We have tried many methods of backup of the SD Card contents. Most of them
appear to work, but in the event, do not actually enable a safe and reliable
restoration. For example:

B1. Win32DiskImager.exe and DiskImage_1_6_WinAll

109
Your Raspberry Pi can be backed up by making an image of the SD Card using one
of the programs. You can use the program to extract the SD Card image by plugging
your card into your PC or Mac and selecting the option that copies the SD Card
image into the same location.

However, we have noted the following problem: the size of the backup image
produced sticks at 4GByte even for a 64GByte SD Card. This cannot be right!

You can restore the image to the SD Card using the same procedure as writing the
OS originally: select the card from the drop down box and then selected the image
file to be restored. However, we have noted the following problems: - on many SD
Cards, the programs may report that the target SD Card is too small, or other errors; after an apparently successful restoration the card does not boot properly, reporting
errors and hanging.

There are several similar programs, and they also seem to fail, at least with larger
cards.

B2. The Best Backup Solution

We have found that a working backup system is that from DiskInternals, named
Linux Reader. This program will locate Linux discs and partitions on Linux discs
and permit copies of whole discs or partitions to be created on any other medium
present. Note that for very large SD Cards, you will need lost of space on the
selected medium.

Once created, your backup disc image can be restored to an SD Card using a
program such as Active Disk Image, or WinImage Administrator. We have
successfully backed up a 64GByte Raspberry Pi Linux SD Card image and restored
it to a 128GByte SD Card using this method. We have not tried restoration to a
similar size SD Card as the original source card.

110
Please note that whilst backups are vital to save time and preserve data, it is unwise
to test the backup on your working SD Card, as it is not unusual for such backup or
the restoration, to fail or to be irretrievable. It is also essential to test the backup restore sequence on a card with as much data on it as you can usefully get.

Part C: Making Serious Use of the Installed Software

Having spent the last several hours installing a powerful suite of server programs
onto your Raspberry Pi, the next task is to start to use the machine seriously.

C1. Copy your Website Files

Actually developing a website is out of the scope of this article as it is not strictly
related to the setting up of your Raspberry Pi. Therefore we are making the
assumption that you already have a website, complete with its content, and you
would like to host it on your Raspberry Pi using the software infrastructure which we
have so far installed and setup.

So, if you have already developed website, you can copy it onto your Raspberry Pi.
To do this, follow this procedure: Use an FTP Client such as WS_FTP95 or similar,
to connect to your Raspberry Pi - a graphical FTP client is generally much easier for
you to use than continuing on the command line. You will need to enter the IP
address of your Pi into your FTP client. If you log into ProFTPd with the Pi
username and password you may not be allowed to make directories or copy the
files. Therefore you will have to extend the default settings of the ProFTPd server on
your Raspberry Pi to allow root login. NB: if you have extended the root login to
ProFTPd for a session, it would be wise to revert afterwards to the standard settings,
which do not permit root to login via FTP remotely. To permit root login to
ProFTPd open PuTTy and login to your Pi as root. Then open the ProFTPd
configuration file in the nano editor: nano

/etc/proftpd/proftpd.conf For tidiness,

first of all set the ServerName directive to your own host name for your Pi
ServerName "yourPiHostname" Then locate the RootLogin directive and change it
to "On", or create the line at the end of the file: RootLogin On Then save the file

111
[Ctrl]+O and exit nano with [Ctrl]+X. Finally, you need to make a change to the
ftpusers file, which contains a list of usernames prohibited from logging in via an
FTP client:

nano

/etc/ftpusers The root user is commonly at the top of the file.

Simply insert a hash symbol (#) at the very beginning of that line to remove the root
user from the prohibited list.

Then save the file [Ctrl]+O and exit nano with

[Ctrl]+X. You will need to stop and restart the ProFTPd service in order for the
changes to take effect: service proftpd stop service proftpd start

Login to your FTP client program and navigate to your Apache2 data directory,
usually /var/www. You must then create a directory for your website - we will name
our site oursite1. Then navigate to the location where you hold your website files and
content and start the process of transfer of all of your website files to your chosen
site directory on your Raspberry Pi /var/www/oursite1.

You will now be able to view your website from your PC by starting a web browser
and typing the following into the address bar:

http://10.0.0.97/oursite1 or

http://raspbianwheezy97/oursite1 but remember to substitute your Pi IP address for


mine, and your Pi hostname for mine, and to enter your Pi hostname into your
Windows host file. Your site is now available, but there are two further
enhancements we can make to your setup: use a virtual hostname and make to site
available outside your network - i.e. go global!

C2. Create a Virtual Host

The snag with the current setup is that your website is seen as a subdirectory of the
website of the hostname. In the case illustrated, oursite1 is a subdirectory of the main
site raspbianwheezy97. What you'd prefer to be able to do is to type http://oursite1
into the address bar of your web browser and have it displayed as though oursite1
was the actual website URL. That can be done by setting up oursite1 as a virtual host
in your Apache2 configuration. A virtual host is simply a name assigned as a website
URL and hosted on your Apache2 server, but with a name independent of your
machine hostname. You can have more than one virtual host if you wish, but we will
set up just one.

112
First, let's stop the Apache2 service - you know how to do this by now. Next, we
need to navigate to the location from where Apache2 will read a new configuration
file containing our setup for a virtual host. cd /etc/apache2/sites-available You can
place all virtual host configuration files here. But each file will not be enabled unless
a symbolic link to the file is created in the parallel directory sites-enabled. There is a
tool for doing this, which we will use once we have created the file. We will call our
configuration file oursites.conf, and we will create it with the nano editor: nano
oursites.conf Note that the oursites is plural, as we may have more than one virtual
site! Then edit the file so that it contains the following text:

# oursites.conf # KA Spencer 201211 # # First, the listening port (if not specified
elsewhere): Listen 80 # # Next, the IP address and port for the virtual host. This
assumes # that you have only one IP address and port for this server. # Be sure to
substitute your own parameters throughout this file! NameVirtualHost 10.0.0.97:80
# # Next, add the default server, because creating a virtual host # causes Apache2 to
ignore the default server configured in the # /etc/apache2/sites-available/default file.
# If you do not do this, any html files in /var/www will be ignored! <VirtualHost
10.0.0.97:80> DocumentRoot /var/www DirectoryIndex index.htm index.html
index.php </VirtualHost> # # Next your first virtual server details: <VirtualHost
10.0.0.97:80>

ServerAdmin

email@youraddress.com

ServerName

oursite1

DocumentRoot /var/www/oursite1 DirectoryIndex index.htm index.html index.php


ErrorLog

/var/www/oursite1/log/error.log

CustomLog

/var/www/oursite1/log/access.log combined </VirtualHost> # This will allow you to


access your "oursite1" website by that name.

For

the

CustomLog

directive,

choose

file

format

defined

in

/etc/apache2/apache2.conf.

There are one or two other configuration adjustments to make before this will work.
First, create a directory for the Apache2 log files, as given in the oursites.conf:
mkdir /var/www/oursite1/log Then we must make a link to our new virtual host file
in sites-enabled. Do this using the a2ensite command: a2ensite oursites.conf This

113
program creates the link for you. Its sister program a2dissite will remove the link if
you wish to take your virtual host site offline.

Finally, it is necessary to enter your new virtual host site name into your Raspberry
Pi /etc/hosts file (see A5.1b), your PC workstation hosts file (see A5.2), or into your
domain name server (DNS) if you have one.

Now if all is well, you can restart the Apache2 server in the usual way. There should
be no errors on startup. If errors occur, stop the Apache2 server and examine each
stage in turn for errors. If everything is correct, when you type http://oursite1 into
your web browser address bar, you should see your website. You have a virtual host
working! Wouldn't it be good if the whole world could see you site - that's possible,
let's see how.

C3. Going Global

Whether or not you can set up your site to be visible in the Internet at large depends
on a number of factors: - do you have ADSL or Fibre Broadband? If you have only
diallup, I must tell you that what we are trying to do is not very reliable under diallup
Internet access! - does your ISP give you a permanent (fixed) IP address? If you do
not know the answer to this question, then ask them! Even if you have a dynamic IP
address it may still be possible to make your site available, but it is easier with a
static address; - does your router support "Port Forwarding"? Most do; - does your
router support "Hairpin Routing"? Possibly the only way to find out is to try it when
your setup is completed. Testing the set up will have to be done on a friend's Internet
connection if your router does not support this mode. Absence of Hairpin Routing
does not mean that you cannot make your Raspberry Pi website available on the
Internet at large, it simply means that it will be out of bounds to your Local Area
Network (LAN) as served by your router. Nearly all Belkin ADSL routers, many
Netgear cable routers are fine. Some BT ADSL routers do not allow Hairpin
Routing.

114
C3.1 Router Setup First, let's setup your router for Port Forwarding. This process
allows your router to pick up TCP data packets that it receives from the Internet,
examine the port number with which the packet is labelled, and then direct the
packet to the correct computer on your network using the target computer's IP
address. Thus all port 80 packets (the standard HTTP port) can be directed uniquely
to your Raspberry Pi. This facility is known variously as Port Forwarding, Virtual
Server, Port Mapping or possibly just as Network Address Translation (which is
slightly incorrect).

First, you need to login to your router using the username and password that has
previously been set up for it. To do this you need the router's LAN IP address. You
can find that by opening a Command Window on your PC, and typing the command
IPCONFIG /ALL. You are interested in the IP Address listed after Default Gateway.
When you have it, open your web browser and type http://RouterIPAddress into the
address bar, but substitute the router IP address for RouterIPAddress. You can then
login to the router. Navigate to the page which enables you to edit the Port
Forwarding or Virtual Server setup. When you locate it, create a new record (if
necessary) and enter the IP Address of your Raspberry Pi and the port number 80
into the record. If you are asked for a TCP or UDP or

TCP+UDP protocol option select TCP+UDP. If you are asked to specify the Port
number for both Remote (WAN) and Local (LAN) port enter 80 for both. Ensure
that you save the router settings, rebooting it if necessary.

To test the router setup, and at the same check on its ability to do Hairpin Routing,
you will need your External or Wide Area Network (WAN) IP Address. This is the
IP address which identifies your router on the Internet at large - the "other" side of
your network. One easy way to get this is to visit a website such as
http://WhatIsMyIP.com. Make a note of your WAN IP address. Then type the
following into the address bar of your browser: http://my-wan-ip-address substituting
your WAN IP address just found for my-wan-ip-address. If all is well, you should
see your website as created on your Raspberry Pi! If you get an error 404 (site not

115
found) it could be that you have made an error in the setup or your router does not do
Hairpin Routing. You can check this using a friend's Internet connection.

C3.2 Getting a Hostname and DNS Having your site accessed by its WAN IP
address is all very well, but not so easy to remember. This is why domain names are
so important on the Internet, and lie at the heart of the World Wide Web. What we
now need to do is to get your site a name, or URL which is linked to your WAN IP
address, so that your URL can be used to access your site. This service is quite
widely available free-of-charge or you can pay for a subscription service. To locate a
service try a Google Search for phrases such as "free dns hosting". Ideally you need
a service which also offers free subdomains as well. What this means is that the
service provides the domain (such as domain.com) and you choose any available and
suitable subdomain such as my-website. When combined this gives you a website
address visible to the world as my-website.domain.com. After you have signed up to
the service, all you have to do is to enter your WAN IP address, and chose your
preferred subdomain and you have your web URL set up.

C3.3 Creating a Server Alias Now that you have your web URL set up you will need
to adjust your configuration of Apache2 to take account of it. This is necessary
because as set up currently, Apache2 will only respond to the ServerName of
oursite1. But you want it to respond also to my-website.domain.com, or whatever
subdomain and domain you have chosen with your DNS service.

First, stop the Apache2 service in the usual way. Then edit your configuration file
oursites.conf as follows: nano oursites.conf You need to add a new directive,
ServerAlias as follows: Locate the line: ServerName oursite1 and create a new
blank line immediately after it, and enter the text:

ServerAlias my-

website.domain.com substituting your new website URL chosen with your DNS
service for my-website.domain.com.

If everything has been done correctly your website is now available world-wide
using your newly created web URL. Your DNS service will watch for web traffic
with your web address and forward it to your router using its WAN IP address. In

116
turn, your router will send the data packets to your Raspberry Pi using its local IP
address. Apache2 will pick up the data and using the web URL to identify your site
by its ServerAlias, it will serve the requested pages back to the original client PC
which could be in Outer Mongolia! And with our nest little setup you'll be able to
see whether anyone in Outer Mongolia has indeed viewed your site!

Next, let's set up Webalizer so that you can see what work your Raspberry Pi is
doing.

C4. Showing your Website Statistics

In section A12 above, you installed the Webalizer program. Unfortunately at present,
Webalizer does not know about the pages being served by your newly setup web
URL and its associated web site.

Apache2 is already placing data in its log files for your site oursite1 (alias mywebsite.domain.com). See the data in the file in /var/www/oursite1/log/access.log by
opening the file in nano. In order to see the access data graphically displayed, you
need to create a subdirectory for the Webalizer graphics and then to make two small
amendments to the Webalizer configuration file.

First create the new directory: mkdir /var/www/oursite1/webalizer Then make the
amendments to the webalizer.conf file by opening it in nano:

nano

/etc/webalizer/webalizer.conf

First, in the webalizer.conf file locate and edit the Apache2 log file entry line
currently:

logfile

/var/log/apache2/access.log

to

logfile

/var/www/oursite1/log/access.log

Finally, locate the line beginning with the directive OutputDir and change it to:
OutputDir /var/www/oursite1/webalizer

117
You may need to stop and start the Apache2 service for these changes to take effect.

Normally Webalizer processes the log files into graphics once each day. If you wish
to see the effects of your changes immediately, just type the command webalizer and
the Apache2 statistical graphics will be updated and ready to be viewed. To view
them enter the following web address into the address bar of your web browser:
http://my-website.domain.com/webalizer.

C5. Secure your Web Statistics against prying eyes

If you wish to to keep your web statistics private, you must password protect access
to the /var/www/oursite1/webalizer directory. To do this first navigate to the
Webalizer directory create an encrypted .htpasswd file containing the username and
password details:

cd

/var/www/oursite1/webalizer

htpasswd

-c .htpasswd

username where username is the username you want to use to permit access to the
statistics. You'll be prompted to enter and retype your password, then the .htpasswd
file will be created. Next create a new file .htaccess in the same directory, using
nano:

nano

.htaccess and add the following lines:

/var/www/oursite1/webalizer/.htpasswd
/var/www/oursite1/webalizer

AuthType

Require

Basic

AuthUserFile
AuthName

valid-user Remember to adjust the

parameters to suit your own site name and directories!

When you next access your Webalizer web statistics directory in your browser, you
will be asked for the username and password!

[Note: you may use this document freely. However, please ensure that you leave the
Author name on

the first and last pages, and that you pass on the document

only in its entirety.]

End of document: Kenneth A Spencer, v20130701

118

Vous aimerez peut-être aussi