You are on page 1of 65

IMPLEMENTATION OF A LOW-COST HOME AUTOMATION SYSTEM

A PROJECT REPORT Submitted by

KURIAN ABRAHAM K.P. SANDEEP RAO

In partial fulfillment for the award of the degree Of

BACHELOR OF ENGINEERING
In COMPUTER SCIENCE ENGINEERING

K.C.G. COLLEGE OF TECHNOLOGY, CHENNAI

ANNA UNIVERSITY: CHENNAI 600 025


APRIL 2009

ANNA UNIVERSITY: CHENNAI 600 025


BONA FIDE CERTIFICATE
Certification that this project report IMPLEMENTATION OF A LOWCOST HOME AUTOMATION SYSTEM is the bona fide work of KURIAN ABRAHAM and K.P. SANDEEP RAO who carried out the project work under my supervision.

SIGNATURE Dr. T. Ravi HEAD OF THE DEPARTMENT

SIGNATURE Dr. T. Ravi SUPERVISOR Professor and Head of the Department

Computer Science & Engineering K.C.G. College Of Technology, Old Mahabalipuram Road, Karapakkam, Chennai 600096

Computer Science & Engineering K.C.G. College Of Technology, Old Mahabalipuram Road, Karapakkam, Chennai 600096

B.E. DEGREE EXAMINATION Date of Examination:

Internal Examiner

External Examiner

iii

ACKNOWLEDGEMENT

We would like to express our gratitude to Dr. Elizabeth Verghese, Chairperson of K.C.G. College Of Technology, who enabled us to complete this project successfully. We express our sincere thanks to Dr. V. Balakrishnan, Principal of K.C.G. College Of Technology, for his encouragement in completing this project. We are grateful to Mr. S. Gnanasekharan, Vice Principal, K.C.G. College Of Technology, for academic guidance regarding this project. We thank the head of our department and our project guide, Dr. T. Ravi, for his valuable suggestions and guidance. We would also like to thank the non-teaching staff for their help and support.

iv

ABSTRACT

Home automation involves introducing a degree of computerized or automatic control to certain electrical and electronic systems in a building. These include lighting, temperature control, security systems, garage doors, etc. A hardware system is installed to monitor and control the various appliances. The system would control the appliances based on its configuration. For example, it could automatically turn on the lights at a specified time in the evening, or it could measure the ambient light using a hardware sensor and turn on the lights when it grows dark. It can also allow a person to control appliances from a remote location, such as over the internet. For example, one could turn on the air conditioning from the office, before leaving for home. This project demonstrates a simple home automation system that allows the user to control it with a wireless device such as a Wi-Fi or Bluetooth enabled mobile phone. A desktop PC is used to run the server software. The system allows the user to control each of the lights and fans individually. It can automatically turn off the main lights and turn on a night lamp at a specified time. By measuring the signal strength, it can detect when the user enters a room and automatically turn on the light and fans, and then automatically turn them off when the user leaves the room.

TABLE OF CONTENTS
CHAPTER NO. TITLE
TABLE OF CONTENTS

PAGE NO. III IV V IX X 1 3 3 4 5 5 5 5 6 6 6 7 7 7 7

ACKNOWLEDGEMENT ABSTRACT TABLE OF CONTENTS LIST OF FIGURES LIST OF ABBREVIATIONS 1 2 INTRODUCTION SYSTEM ANALYSIS 2.1 EXISTING SYSTEMS 2.2 PROPOSED SYSTEM 3 SYSTEM REQUIREMENTS 3.1 SOFTWARE REQUIREMENTS 3.2 HARDWARE REQUIREMENTS 3.3 DEVELOPMENT TOOLS 3.3.1 MICROSOFT VISUAL STUDIO 2005 3.3.2 JAVA ME PLATFORM SDK 3.0 3.3.3 MPLAB IDE FOR PIC MICROCONTROLLERS 3.3.4 HI-TECH PICC-LITE COMPILER 3.3.5 PICPGM PROGRAMMER 1.0.1.4 3.3.6 JDM PROGRAMMER 3.3.7 PLAYSTATION PORTABLE SDK

vi

TABLE OF CONTENTS
CHAPTER NO. 4 TITLE PAGE NO. 8 8 9 9 10 14 16 17 17 18 18 18 18 18 19 19 20 20 20 20 21

SYSTEM DESIGN SPECIFICATION 4.1 DESIGN SPECIFICATION 4.2 DESIGN DIAGRAMS 4.2.1 DATA FLOW DIAGRAM 4.2.2 SEQUENCE DIAGRAMS 4.2.3 USE CASE DIAGRAMS 4.2.4 COMPONENT DIAGRAM

IMPLEMENTATION 5.1 SERVER MODULE 5.1.1 CONNECTED CLIENTS 5.1.2 COM PORT 5.1.3 BLUETOOTH PORT 5.1.4 SERVER PORT 5.1.5 COMMUNICATION LOG 5.1.6 AUTOMATIC TIMING CONTROLS 5.1.7 CONFIGURATION FILE 5.2 MICROCONTROLLER AND HARDWARE MODULE 5.2.1 PIC16F877A MICROCONTROLLER 5.2.2 PIC DEVELOPMENT BOARD 5.2.3 RELAY BOARD 5.2.4 USB-TO-SERIAL BRIDGE

vii

TABLE OF CONTENTS
CHAPTER NO. TITLE 5.3 BLUETOOTH CLIENT MODULE FOR J2ME 5.4 WI-FI CLIENT MODULE FOR LAPTOPS 5.4.1 SERVER ADDRESS 5.4.2 SERVER PORT 5.4.3 CONFIGURATION FILE PAGE NO. 22 23 23 23 24

5.5 WI-FI CLIENT MODULE FOR PLAYSTATION PORTABLE 24 5.5.1 CONFIGURATION FILE 6 TESTING 6.1. SERVER MODULE 6.1.1 CONFIGURATION FILE 6.1.2 EXISTENCE OF PREVIOUSLY SELECTED COM PORT 6.1.3 ACTIVATION OF TIME-BASED PROFILES 6.1.4 UPDATING GUI ON RECEIVING COMMANDS 6.2 MICROCONTROLLER AND HARDWARE MODULE 6.2.1 QUALITY OF MAINS SUPPLY 6.2.2 ELECTRICAL GROUNDING PROBLEMS 6.3 BLUETOOTH CLIENT MODULE FOR J2ME 6.3.1 SEARCHING FOR SERVERS 6.4 WI-FI CLIENT MODULE FOR LAPTOPS 6.4.1 CONFIGURATION FILE 6.4.2 UPDATING GUI ON RECEIVING COMMANDS 25 27 27 27 28 28 28 29 29 29 30 30 31 31 31

viii

TABLE OF CONTENTS
CHAPTER NO. TITLE PAGE NO.

6.5 WI-FI CLIENT MODULE FOR PLAYSTATION PORTABLE 32 6.5.1 GUI RENDERING PROBLEMS 6.5.2 ROUTE EXISTS TO SERVER 6.5.3 CONFIGURATION FILE 7 CONCLUSION 7.1. CONCLUSION 7.2. FUTURE ENHANCEMENTS APPENDIX 1 APPENDIX 2 REFERENCES 32 32 32 34 34 34 35 43 55

ix

LIST OF FIGURES
FIGURE NO. 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 FIGURE NAME
LIST OF FIGURES

PAGE NO. 9 10 11 12 13 14 15 15 16

DATA FLOW DIAGRAM BLUETOOTH CLIENT IN CONTROL WI-FI CLIENT IN CONTROL SERVER IN CONTROL TIME-BASED PROFILE SERVER MODULE CLIENT USE CASE MICROCONTROLLER USE CASE COMPONENT DIAGRAM

LIST OF ABBREVIATIONS
ACRONYM EXPANSION
List of Abbreviations

BTSPP CLR DC EEPROM GUI IDE J2ME JDK JDM JSR MIDP MIPS PSP SDK TTL USB UUID XML

Bluetooth Serial Port Profile Common Language Runtime Direct Current Electrically Erasable Programmable Read-Only Memory Graphical User Interface Integrated Development Environment Java 2 Micro Edition Java Development Kit Jens Dyekjaer Madsen Java Specification Request Mobile Information Device Profile Microprocessor without Interlocked Pipeline Stages Playstation Portable Software Development Kit Transistor-Transistor Logic Universal Serial Bus Universally Unique Identifier Extensible Markup Language

CHAPTER 1 INTRODUCTION

A typical home automation system allows one to control house hold appliances from a centralized control unit. These appliances include lights, fans, air conditioners, television sets, security cameras, electronic doors, computer systems, audio/visual equipment, etc. These appliances usually have to be specially designed to be compatible with each other and with the control unit for most commercially available home automation systems. The project Implementation of a Low-Cost Home Automation System, demonstrates a system that can be integrated into a buildings electrical system and allows one to wirelessly control lights, fans, and turn on or off any appliance that is plugged into a wall outlet. The system can be controlled from a Bluetooth or Wi-Fi enabled device such as a mobile phone or laptop, while a desktop PC acts as the server. Thus the installation cost and hardware cost is kept to a minimum as most users already own the requisite hardware such as a mobile phone and desktop PC. A Bluetooth dongle or a standard Wireless Access Point is used to provide connectivity between the server and the mobile device. The system is capable of detecting when the user enters or leaves the room by measuring the change in signal strength between the Access Point and the mobile device, and can accordingly turn on or off appliances such as lights and fans. The power supply for each appliance is wired through an electromechanical relay. A number of relays are used depending on the number of appliances to be

controlled. All the relays are controlled by a microcontroller. The microcontroller is connected to the server via a USB interface. This makes it plug-and-play and compatible with virtually any PC. The system can be configured with time-based profiles. For example, one could have it automatically turn on the lights at 6:00 in the evening. At 10:00 P.M. it could automatically turn off the main lights and turn on a night lamp. It could then turn off the night lamp the next morning. The server can also receive connections over the internet and can be controlled from a remote location. This opens up many possibilities. For example, one could remotely turn on the air conditioner from the office before leaving so that the room is cool before reaching home.

CHAPTER 2 SYSTEM ANALYSIS

2.1 EXISTING SYSTEMS


Most commercially available home automation systems are all-in-one solutions which require that all controllable appliances are from the same company, or must be approved as compatible with said companys system. Moreover these systems normally come with a proprietary, dedicated device which acts as the control center. To control the system from multiple locations, additional control devices must be purchased. These complex systems usually need to be integrated when the building is constructed and must be planned in advance. They are also difficult to upgrade or replace once installed. The overall investment adds up considerably and is financially infeasible in most cases. These drawbacks hinder the popularity of such systems.

2.2 PROPOSED SYSTEM


The objective of the proposed system is to offer a low-cost solution for a home automation system that overcomes the above drawbacks. The system provides basic control of appliances at a fraction of the cost of commercially available systems. The concept of a proprietary control device is done away with as the system can be controlled from a Bluetooth or Wi-Fi enabled mobile device, such as a mobile phone or laptop. There is no need for a specialized server system as a typical desktop PC can act as the server. Nowadays most users already own the requisites such as a mobile phone and a desktop PC; hence the cost of the system is considerably reduced. The system can be easily integrated into an existing electrical system of a building thanks to its simplified design. It can also be easily installed for just a single room if one so desires. Modifications to the existing electrical system are minimal, thereby reducing installations costs.

CHAPTER 3 SYSTEM REQUIREMENTS

3.1 SOFTWARE REQUIREMENTS


Microsoft Windows 2000 Service Pack 3 or later. Microsoft .NET Framework 2.0 Bluetooth stack supporting BTSPP (Bluetooth Serial Port Profile).

3.2 HARDWARE REQUIREMENTS


Desktop PC running Windows. Bluetooth dongle. Wi-Fi access point or a Wi-Fi adapter for the PC capable of operating in access point mode. If using Bluetooth: Bluetooth equipped mobile phone supporting J2ME (Java 2 Micro Edition) with MIDP 2.0 If using Wi-Fi: Wi-Fi enabled laptop. Sony Playstation Portable is also supported. PIC16F877A microcontroller and development board. Relay board with a number of relays as per requirement.

3.3 DEVELOPMENT TOOLS


A number of different programming tools and languages were used for the development of the various software components of the home automation

system. Since the system involves components that run on different platforms such as a mobile phone, desktop PC etc. the most suitable language for each platform was chosen.

3.3.1 MICROSOFT VISUAL STUDIO 2005 The server application and the Wi-Fi client for Windows are both coded in Microsoft Visual C++ .NET and compiled as a standard Windows executable using CLR (Common Language Runtime) that runs under the .NET Framework.

3.3.2 JAVA ME PLATFORM SDK 3.0 The Bluetooth client for mobile phones is coded in J2ME (Java 2 Micro Edition) using MIDP 2.0 (Mobile Information Device Profile). The JSR-82 API is used for Bluetooth communication. J2ME is the language of choice for the mobile phone client since a predominant number of mobile phones are J2ME enabled.

3.3.3 MPLAB IDE FOR PIC MICROCONTROLLERS The MPLab IDE is used to develop and test the embedded program for the PIC16F877A microcontroller. It provides a simulator that is used to test the communication between the server and the microcontroller before finally programming the microcontrollers EEPROM.

3.3.4 HI-TECH PICC-LITE COMPILER Hi-Tech PICC-Lite is a C compiler for the PIC series of microcontrollers. It is used as the compiler for PIC16 series microcontrollers in the MPLab IDE.

3.3.5 PICPGM PROGRAMMER 1.0.1.4 PICPgm Programmer is the software used to flash the compiled program to the microcontrollers EEPROM and verify that it has been successfully written. It is also used to set the configuration bits on the microcontroller to disable the watchdog timer to prevent it from restarting while waiting in a loop for commands from the server.

3.3.6 JDM PROGRAMMER A 40-pin JDM design programmer is used to connect the microcontroller to the PC for programming the EEPROM.

3.3.7 PLAYSTATION PORTABLE SDK The Wi-Fi client for the Playstation Portable is written in C using the PSPSDK. The GNU C Compiler is used by the PSPSDK to compile to MIPS architecture for the PSP.

CHAPTER 4 SYSTEM DESIGN SPECIFICATION

4.1 DESIGN SPECIFICATION


The system is designed keeping in mind the following key requirements: Clients should be able to quickly and seamlessly connect to and disconnect from the system. Connections from all kinds of clients must be handled simultaneously; i.e. Bluetooth, Wi-Fi and Internet. Change in the status of an appliance should be propagated to all clients in real-time. Customizable time-based profiles to automatically activate and deactivate appliances based on the time of day. Hardware should be widely compatible with different PC configurations. Server should run in the background without disturbing regular activities on the desktop PC. Provide a simple and user-friendly interface on the client side.

4.2 DESIGN DIAGRAMS


4.2.1 DATA FLOW DIAGRAM

Mobile Device

Wi-Fi / Bluetooth

Server

USB-to-Serial Bridge

Microcontroller

Relay System

Electrical System

Figure 4.1 Data Flow Diagram

10

The mobile device connects to the server PC through Bluetooth or Wi-Fi or through the internet. The user sends commands to the server from the mobile device. The microcontroller is connected to the server via USB. On receiving commands from the mobile device, the server sends commands to the microcontroller over the USB connection. The microcontroller is directly connected to the relays and it can enable or disable them. The relays are connected to the electrical system of the building so that they can control the plug points.

4.2.2 SEQUENCE DIAGRAMS

Figure 4.2 Bluetooth Client in Control

11

Figure 4.3 Wi-Fi Client in Control When a Bluetooth or Wi-Fi client connects to the server, the server sends it the current status of the appliances so that it can be displayed on the mobile device. When the user sends a command from the mobile device, the server receives it and forwards it to the microcontroller, and then sends updated status of all the appliances to all the clients connected to the server. Additionally the Wi-Fi client continuously monitors the signal strength, and detects when the user leaves or enters the room according to its configuration, and it can send commands to activate or deactivate appliances.

12

Figure 4.4 Server in Control The server applications interface can be used to directly send commands to the microcontroller and control the appliances.

13

Figure 4.5 Time-Based Profile The time-based profiles are configured on the server interface. The server checks whether its time to activate a particular profile and sends the corresponding commands to the microcontroller to activate or deactivate the corresponding appliances.

14

4.2.3 USE CASE DIAGRAMS


Server
Control Appliance uses uses

uses Customize Time-Based Profile uses Administrator uses Client

uses Activate Time-Based Profile

Propagate Status

Figure 4.6 Server Module The server module receives control commands either from clients or directly from its own interface. The time-based profiles are configured on the server interface. It internally checks whether its time to activate a time-based profile. It propagates the status of the appliances to all connected clients.

15

Figure 4.7 Client Use Case The client interface allows the user to control the appliances. It receives status updates from the server.

Figure 4.8 Microcontroller Use Case The microcontroller only receives commands from the server via USB.

16

4.2.4 COMPONENT DIAGRAM

Figure 4.9 Component Diagram The component diagram shows all the physical components of the entire system and how they are interfaced with each other.

17

CHAPTER 5 IMPLEMENTATION

The system is comprised of five different modules in total; three of which are client modules for different platforms. Server for Windows Embedded Program for Microcontroller, and Hardware Circuit Bluetooth Client for J2ME mobile phones Wi-Fi Client for Windows laptops Wi-Fi Client for Sony Playstation Portable

5.1 SERVER MODULE


The server module is executed on a desktop PC running Windows. It sends commands to the microcontroller to control the relays, and accepts commands from clients connected to it. The push buttons on the left can be used to directly control the relays from the server side without using a client. If the relay is active i.e. the appliance is turned on, the button stays in a depressed position.

18

5.1.1 CONNECTED CLIENTS A list of all the clients connected to the server either through Wi-Fi or through the Internet is show in this list box. It shows the clients IP address and the remote port on the client side.

5.1.2 COM PORT The USB-to-Serial Bridge presents itself as a virtual COM port to the server. The port number that corresponds to the USB-to-Serial Bridge is chosen so that the server can communicate with the microcontroller.

5.1.3 BLUETOOTH PORT The BTSPP protocol also functions through a virtual COM port. The port number that corresponds to the COM port to which the mobile phone is connected to is chosen.

5.1.4 SERVER PORT This is the port on which the server listens for incoming connections from the Wi-Fi network and from the Internet. The clients should also be configured to connect to this port number.

5.1.5 COMMUNICATION LOG It logs all communication between the server and the microcontroller, as well as commands received through Bluetooth from clients.

19

5.1.6 AUTOMATIC TIMING CONTROLS The server can be configured to automatically turn on or off particular appliances at specific times. Up to 14 different configurations for different timings can be set. Each horizontal row corresponds to a particular time and the checkboxes from left to right represent the relays. If the small checkbox inside the time spin box is checked then that time profile is active and the relays will be switched on or off at the corresponding time according to the 8 checkboxes. An empty checkbox means that the corresponding relay will be switched off. A ticked checkbox means that the corresponding relay will be switched on. A partially ticked (shaded) checkbox means that the corresponding relay will not be changed; it will be left unchanged when the profile activates automatically at the corresponding time. For example in the given image at 6:00 PM, Relay 1 (Light 1) and Relay 2 (Light 2) will be switched on and Relay 3 (Night Lamp) will be switched off. The remaining relays will be left unchanged at whatever state they previously were.

5.1.7 CONFIGURATION FILE When the program is closed, the settings are saved in an XML formatted file. The previous settings are loaded the next time the program is launched.

20

5.2 MICROCONTROLLER AND HARDWARE MODULE


5.2.1 PIC16F877A MICROCONTROLLER The microcontroller used is a PIC16F877A manufactured by Microchip Technology Inc. It communicates with the server using Serial communication via a USB-to-Serial Bridge. It has multiple outputs which are used to control the relays. The microcontroller is programmed such that if it receives a lower case a-h it turns off the corresponding relay and if it receives an upper case A-H it turns on the corresponding relay. If it receives any other input it responds with an error saying the input was unrecognized.

5.2.2 PIC DEVELOPMENT BOARD The following development board is used to operate the PIC microcontroller. It provides an external oscillator crystal that is required for the functioning of the microcontroller, as well as easily accessible I/O ports. The development board and microcontroller are powered with +5V through the USB connection to the PC. The UART port on the development board is connected to the USB-to-Serial Bridge.

5.2.3 RELAY BOARD A relay board with eight electromechanical relays is used to switch on and off the appliances. The relay board is connected to one of the output ports on the microcontroller. The relay board requires +12V for operation and is powered by a transformer. If the mains supply delivers low voltage then the transformer voltage may drop below +12V and the relays may not function

21

efficiently. To overcome this, a higher voltage transformer is used and a 7812 voltage regulator is used to deliver a steady +12V to the relay board. The output port on the microcontroller is 8 bits wide. When logical one (+5V) is output on one of the bits, the corresponding relay is activated. The live terminal input of each appliance is wired across the Common and Normally Open terminals of the relays, thus the power to the appliance is switched on or off depending on whether the relay is active or not. For the purpose of demonstrating a working model, three 220V outlets have been attached the relay board. The maximum load switching capacity of each of the relays is given below:
7 amperes @ 125 volts AC 7 amperes @ 12 volts DC 5 amperes @ 240 volts AC 5 amperes @ 28 volts DC

5.2.4 USB-TO-SERIAL BRIDGE The USB-to-Serial Bridge used is based on the Prolific PL2303 chip. It accepts 0 to +5V TTL voltages and outputs the signal on a virtual COM port presented the PC. A MAX232N line driver is used to convert the 0 to +5V TTL levels to RS232 levels. The RS232 voltages are then sent through the PL2303 chip which connects to the PC via USB.

22

5.3 BLUETOOTH CLIENT MODULE FOR J2ME


The Bluetooth client is designed to run on mobile phones that are J2ME and MIDP 2.0 enabled. Nowadays most mobile phones support J2ME as well as MIDP 2.0 hence the user base for the Bluetooth client is very large. This is the most compelling reason to choosing J2ME as the development platform. When the application is started, it attempts to initialize the Bluetooth device. If the mobile phone doesnt have Bluetooth or doesnt support the J2ME Bluetooth API (JSR-82) an error is displayed. On pressing the Search button, it attempts to search for nearby Bluetooth devices and tries to identify the Home Automation Server running on the BTSPP protocol. Once the device discovery is complete, it displays a list of MAC address of any servers it has found. Select the desired server and press the Connect button. Once its connected to the server, it displays a list of appliances and their current status. The appliances can be turned on and off by checking or clearing the corresponding checkboxes. When an appliance is turned on or off, the server propagates the status to all the other clients connected to it. Similarly if an appliance is turned on or off from another client, the status is updated on the mobile phone in real-time.

23

Pressing the Disconnect button ends the BTSPP connection and returns to the Search screen.

5.4 WI-FI CLIENT MODULE FOR LAPTOPS


The Wi-Fi Client for laptops is visually similar to the server module and is designed to run on Windows. The push buttons on the left are used to activate or deactivate the relays and hence the appliances connected to them. On clicking on one of the buttons to activate it, a command is sent to the server to activate the corresponding relay. Only if the server responds confirming that the relay has been activated does the button stay depressed on the client interface.

5.4.1 SERVER ADDRESS The IP address of the home automation server to connect to is provided here. This can even be an IP address on the internet, thus allowing one to control the connected appliances from a remote location such as from ones office.

5.4.2 SERVER PORT The remote port on the server to connect to is provided here. This must be the same port that the server is configured to listen on.

24

5.4.3 CONFIGURATION FILE When the program is closed, the settings are saved in an XML formatted file. The previous settings are loaded the next time the program is launched.

5.5 WI-FI CLIENT MODULE FOR PLAYSTATION PORTABLE


The Wi-Fi client for the PSP uses the PSPs built-in Wi-Fi adapter to connect to the Home Automation Server. The client is coded in C and is compiled as a native application. Hence it is possible to query low level information about the Wi-Fi connection such as the signal strength etc. By measuring the change in signal strength when the device moves towards and away from the Wi-Fi access point, it is possible to determine when one leaves the room or enters the room. The system can perform automated tasks when these events occur, such as automatically turning off the lights when one leaves the room and automatically turning on the lights when one enters the room. Pressing the Start button connects to the access point specified in the configuration file and attempts to connect to the configured server IP. Once it has successfully connected to the access point, the signal strength is displayed as percentage in the upper left corner of the screen. As the device is moved towards or away from the access point, the signal strength is updated. If the signal strength falls from a higher value to a value below the threshold value, the leave room event is called. If the signal strength increases from a lower value to a value higher than the threshold value, the enter room event is fired. These events can be mapped to any action such as turning

25

on specific relays or turning off certain relays or leaving some relays unchanged. Once it is connected to the server, select the appliance to control using the Up / Down keys and press X to select it. Select On or Off for the chosen appliance and press X to confirm. The status of the appliance is automatically updated on screen, and is propagated to all other clients.

5.5.1 CONFIGURATION FILE A configuration file named config.cfg is used to store settings for the client. A sample configuration file is shown below.
autoon = ABCDEFGH host = 192.168.2.3 autooff = abcdefgh config = 1 threshold = 90 port = 20000

autoon lists the relays that should be changed when the Enter Room event occurs. Upper case letters will turn on the corresponding relays and lower case letters will turn off the corresponding relays. Omitting a letter from A-H will leave that relay unchanged. autooff uses the same format as autoon, except it fires when the leave room event occurs.

26

host is the IP address of the server to connect to. port is the remote port on the server to connect to. config determines which access point from the available network configurations it will attempt to connect to. The host address should be accessible from the subnet of the chosen network configuration. threshold is the value that the signal strength should fall below or rise above in order to trigger the leave room or enter room events.

27

CHAPTER 6 TESTING

Each of the modules was tested using both black box and white box testing techniques. Black box testing ensures the correctness of the systems output, given various possible inputs. White box testing involves providing calculated inputs so that the internal structure of the system can be verified to be error free. For example, white box testing of a software module involves providing different inputs that test all possible code paths within the program. The modules were designed keeping in mind all possible inputs and any erroneous inputs as well. Any exceptions that occur are handled appropriately without compromising the stability of the system. Different issues, both foreseen and unforeseen, were encountered during the design process. These issues and the measures that were adopted to overcome them are described in this chapter.

6.1. SERVER MODULE


6.1.1 CONFIGURATION FILE When the application is launched it reads the previous settings from an XML formatted configuration file. All the values read are checked to be valid for the corresponding data type, and whether they are within their allowed upper and lower bounds if any. If a particular option is corrupted or not present in the

28

configuration file (due to a user manually editing it), a safe default value is assumed.

6.1.2 EXISTENCE OF PREVIOUSLY SELECTED COM PORT Its possible that a COM port that was previously used for communication with the microcontroller which was saved in the configuration file no longer exists the next time the application is started. This may occur if the microcontroller is plugged into a different USB port from last time, in which case Windows will assign it to a different virtual COM port. To prevent an error the COM ports are enumerated and the last used port is activated only of it still exists in the current enumeration.

6.1.3 ACTIVATION OF TIME-BASED PROFILES The system checks whether its time to activate a profile by comparing the current time with the profiles activation time. However there is a possibility that the comparison is incorrect when the current time wraps around to 00:00:00 for the next day/month/year. The calculation is modified to account for such situations.

6.1.4 UPDATING GUI ON RECEIVING COMMANDS Incoming commands from the network are received in a separate network thread. When a command to activate or deactivate a relay is received, the corresponding push button needs to be changed. However since the .NET form engine runs in a separate thread, it is unsafe to modify the buttons directly from the network thread. To overcome this, a delegate function had to be implemented to update the buttons from within the context of the forms thread.

29

6.2 MICROCONTROLLER AND HARDWARE MODULE


6.2.1 QUALITY OF MAINS SUPPLY The electromagnetic relays require a stable +12V DC supply in order to function reliably. Initially a transformer with a rectifier was used to provide a +12V DC supply from the mains. However the quality of the mains supply is unreliable because at times the supply is at a low voltage instead of 220V. This was causing the transformer to output only 9-10V and some of the relays would not activate. To compensate for this, a transformer with a higher output voltage of +16V is used. The transformer output is connected to a 7812 positive voltage regulator IC to produce a stable +12V DC for the relays.

6.2.2 ELECTRICAL GROUNDING PROBLEMS During tests it was found that the microcontroller randomly reset itself and in some cases even had its EEPROM erased, which required it to be reprogrammed. In a normal USB connection the outer mesh wrapping acts as a ground wire. It provides grounding for the device being connected by bridging it to the grounding of the PC. It was assumed that this would absorb and stray currents in the hardware circuit. The USB cable used to connect the microcontroller to the PC is a Type A (Data + Power) to Type A (Data + Power) + Type A (Power only) cable. The single data connector side is connected to the PC and the other data connector is connected to the USB-to-Serial Bridge, while the Power only connector is connected to the microcontroller to provide +5V DC. On further investigation it was found that the USB specification required that the ground wire join exactly two end points. In this case, only the two data

30

connectors were joined by the ground wire, and the ground wire on the Power connector was not connected to the PCs ground. Thus stray currents from the transformer were flowing through the circuit and were triggering the reset pin on the microcontroller. The PIC16F877A microcontroller has a feature called LVP (Low Voltage Programming) which allows the microcontroller to be programmed from a low voltage serial port usually found on laptops, instead of the higher voltage range of the RS232 standard. If a continuous low voltage is applied to the LVP pins for a few seconds, the microcontroller erases its EEPROM and enters programming mode. The stray currents were also activating the LVP mode at times and were causing the microcontrollers EEPROM to get erased. The power plug was changed to a three pin top and a direct connection to the wall outlets ground pin was provided to absorb the stray currents.

6.3 BLUETOOTH CLIENT MODULE FOR J2ME


6.3.1 SEARCHING FOR SERVERS Normally when a Bluetooth service is created, a unique UUID is provided at the time of creation so that the client side can be preprogrammed to connect to discovered services which match that UUID directly. However when the BTSPP service is hosted by the PC, it hosts multiple services using the same UUID, each of which correspond to a different virtual COM port. Thus when connecting via Bluetooth normally, the mobile phone will automatically choose the first service with the matching UUID that it locates. However this may not be connected to the same virtual COM port that the server is listening on. Hence an additional step must be presented to the user on the mobile phone where the

31

specific service to connect to must be selected. Once device discovery and service discovery have completed completely, a list of all MAC addresses that match the match the same UUID are presented to the user. Since the same UUID is repeated amongst the PCs services itself, all the MAC addresses in the list will be the same, each one corresponding to a different virtual COM port. The user must then choose one among these to connect to. Coincidentally the list of MAC addresses appear in ascending order of the name of the virtual COM ports on the server, so it is trivial to choose the correct address since it is known which virtual COM port the server is listening on.

6.4 WI-FI CLIENT MODULE FOR LAPTOPS


Some of the issues encountered in the server application were also prevalent in the laptop Wi-Fi client.

6.4.1 CONFIGURATION FILE When the application is launched it reads the previous settings from an XML formatted configuration file. All the values read are checked to be valid for the corresponding data type, and whether they are within their allowed upper and lower bounds if any. If a particular option is corrupted or not present in the configuration file (due to a user manually editing it), a safe default value is assumed.

6.4.2 UPDATING GUI ON RECEIVING COMMANDS Incoming commands from the network are received in a separate network thread. When a command to activate or deactivate a relay is received, the corresponding push button needs to be changed. However since the .NET form

32

engine runs in a separate thread, it is unsafe to modify the buttons directly from the network thread. To overcome this, a delegate function had to be implemented to update the buttons from within the context of the forms thread.

6.5 WI-FI CLIENT MODULE FOR PLAYSTATION PORTABLE


6.5.1 GUI RENDERING PROBLEMS When the various menus were shown and hidden as the user selected options on the screen, it eventually caused problems such as some menu items not being rendered properly or menus not appearing at all. This was attributed to the system running out of memory to render correctly with all the objects loaded at once. The solution was to dynamically create and destroy each of the menus and other items on screen such as the status texts.

6.5.2 ROUTE EXISTS TO SERVER Even when the PSP is connected to a Wi-Fi access point, its unsafe to assume that the server is reachable. The access point might be on a different subnet and there may not be a network route to the servers IP address specified in the configuration file. The server is assumed to be reachable only when a dummy UDP packet is sent and a reply containing the current status of all the appliances is successfully received from the server.

6.5.3 CONFIGURATION FILE When the application is launched it reads the previous settings from a plain text configuration file. All the values read are checked to be valid for the corresponding data type, and whether they are within their allowed upper and

33

lower bounds if any. If a particular option is corrupted or not present in the configuration file, a safe default value is assumed.

34

CHAPTER 7 CONCLUSION

7.1. CONCLUSION
The home automation system has been experimentally proven to work satisfactorily by connecting sample appliances to it and the appliances were successfully controlled from a wireless mobile device. The Bluetooth client was successfully tested on a multitude of different mobile phones from different manufacturers, thus proving its portability and wide compatibility. Thus a low-cost home automation system was successfully designed, implemented and tested.

7.2. FUTURE ENHANCEMENTS


A useful feature would be to add support for remotely controlling an infrared transmitter. This transmitter can be placed within range of an infrared enabled appliance such as an air conditioner. The user would then be able to control more advanced features of the appliance such as temperature control, fan speed, etc.

35

APPENDIX 1 CODING

1. SERVER MODULE (NETWORK THREAD)


System::Void ServerCommon::ReceiveThread(void) { IPEndPoint^ sender = gcnew IPEndPoint(IPAddress::Any, 0); EndPoint^ senderRemote = safe_cast<EndPoint^>(sender); IPEndPoint^ iplocalep = gcnew IPEndPoint(IPAddress::Any, int::Parse(spnPort->Text)); EndPoint^ localep = safe_cast<EndPoint^>(iplocalep); sock = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp); try { sock->SetSocketOption(SocketOptionLevel::Socket, SocketOptionName::ReuseAddress, 1); sock->Bind(localep); UdpPortOpen = true; } catch (Exception^ e) { MessageBox::Show(e->ToString()); return; } array<unsigned char, 1>^ msg = gcnew array<unsigned char, 1>(50); while (UdpPortOpen) { try { int bytesRead = sock->ReceiveFrom(msg, senderRemote); if (bytesRead > 0) { String^ client = senderRemote->ToString(); if (!lstClients->Items->Contains(client)) { AddListString(client); } DontSend = true; for (int i = 0; i < bytesRead; i++) { for (int j = 0; j < 8; j++) { if (msg[i] == j + 'A') {

36

SetControlPropertyValue(chkRelay[j], "Checked", true); break; } else if(msg[i] == j + 'a') { SetControlPropertyValue(chkRelay[j], "Checked", false); break; } } } SendAll(); DontSend = false; } } catch (...) { //MessageBox::Show(e->ToString()); } } }

2. MICROCONTROLLER AND HARDWARE MODULE


#include <stdio.h> #include <htc.h> #include "usart.h" /* A simple demonstration of serial communications which * incorporates the on-board hardware USART of the Microchip * PIC16Fxxx series of devices. */ __CONFIG(HS & WDTDIS); void main(void) { unsigned char input; INTCON=0; // purpose of disabling the interrupts. // set up the USART - settings defined in usart.h

init_comms(); ADCON1 = 0x06; TRISA = 0x00; PORTA = 0x00; TRISD = 0x00; PORTD = 0x00;

// // // //

make all PORTA initialize all make all PORTD initialize all

bits bits bits bits

output to ON output to OFF

printf("A-H to turn on, a-h to turn off:\r\n"); while(1) { input = getch(); if ((input >= 'A') && (input <='H')) { switch(input)

37
{ case 'A': RD0 = 1; RA0 = 1; break; case 'B': RD1 = 1; RA1 = 1; break; case 'C': RD2 = 1; RA2 = 1; break; case 'D': RD3 = 1; RA3 = 1; break; case 'E': RD4 = 1; RA4 = 1; break; case 'F': RD5 = 1; RA5 = 1; break; case 'G': RD6 = 1; break; case 'H': RD7 = 1; } printf("[%c] on.\r\n", input); } else if ((input >= 'a') && (input <='h')) { switch(input) { case 'a': RD0 = 0; RA0 = 0; break; case 'b': RD1 = 0; RA1 = 0; break; case 'c': RD2 = 0; RA2 = 0; break; case 'd': RD3 = 0; RA3 = 0; break; case 'e': RD4 = 0; RA4 = 0; break; case 'f': RD5 = 0; RA5 = 0; break;

38
case 'g': RD6 = 0; break; case 'h': RD7 = 0; } printf("[%c] off.\r\n", input); } else { printf("[%c] unrecognized.\r\n", input); } } }

3. BLUETOOTH CLIENT MODULE FOR J2ME (RELAY CONTROL)


public void itemStateChanged(Item item) { if (item == chkRelay) { int c=0; byte[] msg = new byte[8]; for (int i=0; i<RELAY_COUNT; i++) { if (chkRelay.isSelected(i) != relayState[i]) { relayState[i] = chkRelay.isSelected(i); if (relayState[i]) { msg[c] = (byte)((int)'A'+i); } else { msg[c] = (byte)((int)'a'+i); } c++; } } if (!dontSend) { bt_client.send(msg, c); } return; } } public void commandAction(Command c, Displayable d) { if (c == EXIT_CMD) { destroyApp(true); notifyDestroyed(); return; } if (c == SCR_MAIN_SEARCH_CMD)

39
{ Form f = new Form("Home Automation"); f.addCommand(SCR_SEARCH_CANCEL_CMD); f.setCommandListener(this); f.append(new Gauge("Searching for servers...", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING)); Display.getDisplay(this).setCurrent(f); bt_client.requestSearch(); return; } if (c == SCR_SEARCH_CANCEL_CMD) { bt_client.cancelSearch(); Display.getDisplay(this).setCurrent(frmConnect); return; } if (c == SCR_LIST_BACK_CMD) { bt_client.requestConnect(-1); Display.getDisplay(this).setCurrent(frmConnect); return; } if (c == SCR_LIST_CONNECT_CMD) { Form f = new Form("Home Automation"); f.addCommand(SCR_CONNECT_CANCEL_CMD); f.setCommandListener(this); f.append(new Gauge("Connecting to server...", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING)); Display.getDisplay(this).setCurrent(f); bt_client.requestConnect(lstServers.getSelectedIndex()); return; } if (c == SCR_CONNECT_CANCEL_CMD) { bt_client.requestDisconnect(); Display.getDisplay(this).setCurrent(lstServers); return; } if (c == SCR_RELAY_DISCONNECT_CMD) { bt_client.requestDisconnect(); Display.getDisplay(this).setCurrent(lstServers); return; } isInit = true; }

4. WI-FI CLIENT MODULE FOR LAPTOPS (NETWORK THREAD)


System::Void ClientCommon::ReceiveThread(void) { sock = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);

40
try { sock->SetSocketOption(SocketOptionLevel::Socket, SocketOptionName::ReuseAddress, 1); sock->Connect(txtServer->Text, int::Parse(spnPort->Text)); UdpPortOpen = true; sock->Send(gcnew array<unsigned char, 1>{'x'}); } catch (Exception^ e) { MessageBox::Show(e->ToString()); return; } array<unsigned char, 1>^ msg = gcnew array<unsigned char, 1>(50); while (UdpPortOpen) { try { int bytesRead = sock->Receive(msg); if (bytesRead > 0) { DontSend = true; for (int i = 0; i < bytesRead; i++) { for (int j = 0; j < 8; j++) { if (msg[i] == j + 'A') { SetControlPropertyValue(chkRelay[j], "Checked", true); break; } else if(msg[i] == j + 'a') { SetControlPropertyValue(chkRelay[j], "Checked", false); break; } } } DontSend = false; } } catch (...) { //MessageBox::Show(e->ToString()); } } } private: System::Void chkRelay_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { int index = Int32::Parse(((CheckBox^) sender)->Tag>ToString()); array<unsigned char, 1>^ s = gcnew array<unsigned char, 1>(1);

41
if (chkRelay[index]->Checked) { s[0] = 'A' + index; } else { s[0] = 'a' + index; } if (!common->DontSend) { common->SendSock(s, 1); } }

5. WI-FI CLIENT MODULE FOR PLAYSTATION PORTABLE (NETWORK THREAD)


int OnOffMenuSelect(int enter) { if (enter) { if (bConnected) { unsigned char msg; switch (vlfGuiCentralMenuSelection()) { case 0: msg = 'A' + (unsigned char)g_relaySel; sceNetInetSend(g_sock, &msg, 1, 0); break; case 1: msg = 'a' + (unsigned char)g_relaySel; sceNetInetSend(g_sock, &msg, 1, 0); break; } vlfGuiSetRectangleFade(0, 56, 480, 272 - 56, VLF_FADE_MODE_OUT, VLF_FADE_SPEED_SUPER_FAST, 0, NULL, NULL, 0); vlfGuiSetTextFadeFinishCallback(relayname, OnOffFadeOut, NULL, 0); return VLF_EV_RET_REMOVE_HANDLERS; } vlfGuiMessageDialog("No connection to Home Automation Server.", VLF_MD_TYPE_ERROR); return VLF_EV_RET_NOTHING; } vlfGuiSetRectangleFade(0, 56, 480, 272 - 56, VLF_FADE_MODE_OUT, VLF_FADE_SPEED_SUPER_FAST, 0, NULL, NULL, 0); vlfGuiSetTextFadeFinishCallback(relayname, OnOffFadeOut, NULL, 0); return VLF_EV_RET_REMOVE_HANDLERS; } int recv_thread(SceSize args, void *argp) { char buf[50]; int readbytes;

42

while(bConnected) { readbytes = sceNetInetRecv(g_sock, buf, 50, 0); if (readbytes <= 0) break; int i, j; for (i = 0; i < readbytes; i++) { for (j = 0; j < 8; j++) { if (buf[i] == 'A'+j) { g_relayStatus[j] = 1; if (OnOff[j] != NULL) { vlfGuiSetText(OnOff[j], "ON"); } break; } else if (buf[i] == 'a'+j) { g_relayStatus[j] = 0; if (OnOff[j] != NULL) { vlfGuiSetText(OnOff[j], "OFF"); } break; } } } } th_recv = -1; return sceKernelExitDeleteThread(0); }

43

APPENDIX 2 SCREENSHOTS

Figure A2.1

Server Main Window

44

Figure A2.2

Server Configuration Window

45

Figure A2.3

Server Time-Base Profile Configuration Window

46

Figure A2.4

Pin Diagram for PIC16F877A

47

Figure A2.5

PIC Development Board Diagram

48

Figure A2.6

PIC Development Board with Microcontroller

Figure A2.7

Relay Board

49

Figure A2.8

Automated 220V Outlets

Figure A2.9

USB-to-Serial Bridge

50

Figure A2.10

J2ME Bluetooth Initialized

Figure A2.11

J2ME Bluetooth Searching

51

Figure A2.12

J2ME Bluetooth Server Addresses

Figure A2.13

J2ME Bluetooth Control Appliances

52

Figure A2.14

Wi-Fi Client for Windows

Figure A2.15

PSP Wi-Fi Client

53

Figure A2.16

PSP Wi-Fi Client Connected

Figure A2.17

PSP Wi-Fi Client Activate Appliance

Figure A2.18

PSP Wi-Fi Client Status Updates

54

Figure A2.19

PSP Wi-Fi Connection Error

55

REFERENCES

1. 2. 3. 4.

.NET Framework Developer Center http://msdn.microsoft.com/en-us/netframework/default.aspx HI-TECH Software: Embedded C Compilers and Tools for Software Development http://www.htsoft.com/ Java ME Technology http://java.sun.com/javame/technology/index.jsp Playstation Programming http://ps2dev.org/

You might also like