Académique Documents
Professionnel Documents
Culture Documents
1/07)
Title
CONFIDENTIAL
RESTRICTED
OPEN ACCESS
specified
by
the
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
Date
20 JULY 2014
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
Date
20 June 2014
iii
To my beloved mother and father who always there for me Hasliza binti Mat Hashim
and Mohamad bin Tomin
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.
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
,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
viii
2.3
10
2.4
11
2.5
Networking System
11
2.5.1
11
2.6
2.7
The Router
System Implementation
13
2.6.1
14
2.6.2
Sensor Nodes
16
2.6.2.1
ZigBee
16
2.6.2.2
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
29
30
3.2.2
31
3.3
Software Specification
System Design
33
3.3.1
Home Network
36
3.3.2
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
45
ix
4.3
48
4.3
4.4
4.5
4.6
51
page
54
Summary
56
DISCUSSION
5.1
Introduction
57
5.2
57
5.3
62
5.4
62
5.5
Summary
63
CONCLUSION
6.1
Introduction
64
6.2
Conclusion
64
6.3
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
2.2
10
2.3
19
2.4
21
2.5
21
2.6
24
3.1
3.2
31
3.3
32
7.1
68
7.2
69
7.3
70
7.4
71
xii
LIST OF FIGURES
FIGURE NO.
TITLE
PAGE
1.1
Flowchart of methodology
2.1
12
2.2
14
2.3
15
2.4
15
2.5
15
2.6
16
2.7
18
2.8
22
2.9
23
2.10
Dsecription of Raspberry Pi
23
2.11
2.12
26
2.13
26
3.1
28
3.2
3.3
3.4
34
3.5
36
3.6
37
3.7
38
3.8
41
xiii
3.9
42
4.1
4.2
44
4.3
4.4
46
4.5
4.6
47
4.7
4.8
4.9
50
4.10
53
4.11
53
4.12
54
4.13
54
4.14
55
5.1
57
5.2
58
5.3
Experiment procedure
59
5.4
59
5.5
60
5.6
62
xiv
LIST OF ABBREVIATION
API
AP
Access Point
FIFO
FTP
GPIO
ISM
IEEE
MCB
MCU
OSI
OS
Operating System
PLC
PSRR
RF
Radio Frequency
RAM
SPI
TNB
USB
LIST OF APPENDICES
APPENDIX
TITLE
PAGE
73
90
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,
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.
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.
ii.
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.
ii.
iii.
iv.
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.
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.
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
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
Example
Temperature monitoring, lamp switch,
home surveillance, power monitoring
Application interfaces
Types of networking
Centralizing control
11
2.4
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
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.
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.
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.
2.6.1
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.
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.
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 [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
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
Indoor/Urban range
30 m
TBD
Outdoor RF line-of-sight
90 m
TBD
range
18
2.6.2.2
19
Table 2.3: nRF24L01 module capability
Features
Radio
Explanation
126 RF channels
GFSK modulation
Transmitter
Receiver
RF Synthesizer
12.3mA at 2Mbps
Enhanced ShockBurst
Power Management
20
Host Interface
Max 8Mbps
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.
Address
Data
CRC
1 Byte
3-5 Byte
1-32 Byte
0-2 Byte
21
multi-chip transmission rate of about 6Mbps. This system allows to send high quality
images in the media wirelessly.
Number of
chips
chip)
6700Kbps
2Mbps
1.98
3.9Mbps
5.8
5.9Mbps
8.86
2.6.2.3
Bluetooth
22
2.6.3
Home Platform
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.
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
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
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].
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
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.
UbiLense
2.7
Summary
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.
29
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
30
3.2.1
Hardware Specification
Table 3.1: Hardware specification for the Smart Home Wireless Power Monitoring
system
No.
Device type
Function
Voltage regulator
Current sensor
(ACS712)
4
nRF24L01
Single Set
Computer
Raspberry Pi
31
Figure 3.2: System Architecture Of Smart Home Wireless Power Monitoring System
device
3.2.2
Software Specification
No.
Component
1.
Raspberry Pi
2) MySql
Laptop
1) Arduino
2.
Software configuration
2) Xamp (Mysql,Apache)
3) Adope webviewer
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.
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.
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
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
End
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
38
3.3.2
39
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.
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
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
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
End
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
Monitoring System
4.2
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.
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.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
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
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
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
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.
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));
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
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.
55
56
4.6
Summary
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
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
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.
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
61
figure 5.5 shows the step to read the current sensor. The rest of the source code will
be shown in Appendix A.
62
5.3
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
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.
5.5
Summary
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
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.
6.3
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;
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.
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
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
RM1.50
3m
RM4.50
(green)
permeter
RM1.50
3m
RM4.50
(red)
permeter
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.
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]
[2]
[3]
[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]
[6]
[7]
H. Shang and R. Xu, A Smart Home System Based On ZigBee And IOS
Software, pp. 37, 2012.
[8]
[9]
[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
#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;
unsigned
long
numSamples
250UL;
unsigned
sampleTime/numSamples;
long
sampleInterval
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
78
int message_print(float data1, float data2, float data3
,char*
sensorStatus)
//data
use
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
}
}
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
(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
81
}
}
//<<<<<<<<<<<<<<<message_send function>>>>>>>>>>>>>>>
void message_send()
{
dtostrf(rms_1, 4, 2, str1);
//itoa(rms,
str,
10);
//integer
to
string
itoa(int
rms_1
,rms_2
,rms_3
,"
(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
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() ;
}
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)(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
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]
=
=
=
=
= 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();
}
101
APPENDIX C
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.
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.
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
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
configurations necessary before you can use phpMyAdmin. First edit the php.ini file
to include a MySQL library:
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:
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.
Add
the
following
http://download.webmin.com/download/repository
two
sarge
nano
lines:
deb
contrib
deb
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
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:
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.
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.
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.
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
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
Simply insert a hash symbol (#) at the very beginning of that line to remove the root
user from the prohibited list.
[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
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
/var/www/oursite1/log/error.log
CustomLog
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.
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.
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.
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
/var/www/oursite1/webalizer/.htpasswd
/var/www/oursite1/webalizer
AuthType
Require
Basic
AuthUserFile
AuthName
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
118