PROJECT REPORT ON
MULTI UTILITY SENSOR NETWORK HOST SOFTWARE DESIGN
SUBMITTED BY
DEEP BHATTACHARJEE SANKET HASE SHAUVIK ROY CHOUDHARY PARAG SHAH IN PARTIAL FULFILLMENT OF THE REQUIREMENTS OF THE DEGREE OF BACHELOR OF ENGINEERING IN COMPUTERS IN THE UNIVERSITY OF MUMBAI
UNDER THE GUIDANCE OF
PROF. K. G. BALAKRISHNAN
DEPARTMENT OF COMPUTER ENGINEERING VIVEKANAND EDUCATION SOCIETY’S INSTITUTE OF TECHNOLOGY CHEMBUR, MUMBAI-400071
UNIVERSITY OF MUMBAI 2005-2006
PROJECT REPORT ON
MULTI UTILITY SENSOR NETWORK HOST SOFTWARE DESIGN
SUBMITTED BY
DEEP BHATTACHARJEE SANKET HASE SHAUVIK ROY CHOUDHARY PARAG SHAH IN PARTIAL FULFILLMENT OF THE REQUIREMENTS OF THE DEGREE OF BACHELOR OF ENGINEERING IN COMPUTERS IN THE UNIVERSITY OF MUMBAI
UNDER THE GUIDANCE OF
PROF. K. G. BALAKRISHNAN
DEPARTMENT OF COMPUTER ENGINEERING VIVEKANAND EDUCATION SOCIETY’S INSTITUTE OF TECHNOLOGY CHEMBUR, MUMBAI-400071
UNIVERSITY OF MUMBAI 2005-2006
A Tribute to Deep S. Bhattacharjee
Deep S. Bhattacharjee was a brilliant and one of the finest students of Vivekanand Education Society's Institute of Technology, where he was pursuing his Bachelor of Engineering (B.E.) in Computer Engineering. A very sincere and hardworking student by nature, Deep always excelled in studies and was a topper of his class consistently. He was very jolly and always ever ready to help his friends and colleagues in their time of need. Unfortunately, Deep left us in a tragic accident during the floods of 26th July 2005. This project is an earnest tribute by his friends to a life which our world was blessed with for so tragically short a time. Our heartfelt prayers are with his family and friends on this occasion of unspeakable grief. May his soul rest in peace!
We dedicate this project in loving memory of our very own Deep S. Bhattacharjee
ii
Vivekanand Education Society’s
INSTITUTE OF TECHNOLOGY Sindhi Society, Chembur, Mumbai-400 071
CERTIFICATE OF APPROVAL OF PROJECT WORK
This is to Certify that ___________________________ __________________ has satisfactorily carried out the project work entitled ___________________________ __________________________ in partial fulfillment of the B.E. Degree in ______________ of the University of Mumbai, Maharashtra state during __________.
PRINCIPAL
PROJECT GUIDE
HEAD OF DEPARTMENT
EXAMINER
iii
Acknowledgements No project of such scope can be developed without the support of many people. And this project is no exception. We are especially grateful to Prof. K.G. Balakrishnan and Prof. Abhay Kshirsagar for guiding us throughout and supporting us relentlessly. They are more than just project guides to us. For providing the necessary facilities and the proper atmosphere within which to work, we wish to thank the Management of Vivekanand Education Society’s Institute of Technology. We are indebted to the Management for helping us stage our project at the international project exhibition ‘ELECRAMA 2006’. Thank you for having faith in us. And a special word of thanks to Mr. Mishra for perennially keeping us on our toes and giving us some fantastic moments and practical advices to cherish; before, during and after ‘ELECRAMA 2006’. We would like to acknowledge the support of all the professors and staff at VESIT. Their encouragement and comments helped us complete the project. To name them all is impossible, but we especially thank Chandrashekhar Sir, for working relentlessly to make our boards; Rajesh Sir, for all the support in Lab 214; Chandane Sir, for the cooperation extended in 001, the Development Lab; and Purohit Sir for making us see all the waveforms in our network. Our sincere thanks go to Dr. D. V. Gadre, Assistant professor at NSIT, New Delhi for showing us the way and pushing us in the right direction. We are obliged to him for sharing his profound knowledge and resources for AVR microcontroller. We also take this opportunity to thank all the anonymous industrialists, managers, engineers and visitors for taking interest in our project at ‘ELECRAMA 2006’. Their comments and suggestions have changed the course of our project. To twist an old cliché, “They are not valuable, they are priceless.” Last, and obviously not the least, we would like to acknowledge our families and friends for their support and patience. They have provided us with all the strength to go ahead, even as they suffered our absence. We can only hope that as they view the final outcome, they feel that their sacrifices were worth it.
iv
Table Of Contents 1
General Overview........................................................................................................ 1 1.1
Introduction ......................................................................................................... 2
1.2
Structure of the network...................................................................................... 3
1.2.1
RS-485 Bus ..................................................................................................... 3
1.2.2
Sensor Nodes................................................................................................... 4
1.2.3
RS-232 to RS-485 Bridge ............................................................................... 5
1.2.4
Host computer ................................................................................................. 5
1.3
2
3
1.3.1
Hardware Implementation............................................................................... 6
1.3.2
Embedded software Implementation............................................................... 6
1.3.3
Host software Implementation ........................................................................ 6
Host Software Introduction ......................................................................................... 7 2.1
Problem definition............................................................................................... 8
2.2
Need of "Sensor Network Management Software” ............................................ 9
2.2.1
Data Acquisition.............................................................................................. 9
2.2.2
Data Analysis .................................................................................................. 9
Software Requirement Specification......................................................................... 10 3.1
Software Requirements ..................................................................................... 11
3.1.1
Hardware Requirements................................................................................ 11
3.1.2
Software Requirements ................................................................................. 11
3.1.3
User Interfaces............................................................................................... 12
3.1.4
User Constraints ............................................................................................ 12
3.2 4
Project Divisions ................................................................................................. 6
Use Case Diagram............................................................................................. 13
System Design........................................................................................................... 14 4.1
Identifying modules of the system .................................................................... 15
4.2
Description of modules and their interaction .................................................... 17
4.2.1
User Interface (UI) ........................................................................................ 17
4.2.2
Distribution Protocol (DP) ............................................................................ 17
4.2.3
Database Module (DB).................................................................................. 17
4.2.4
Pattern generation (PG)................................................................................. 18 v
4.3
5
4.3.1
User Interface (UI) ........................................................................................ 19
4.3.2
Distribution Protocol (DP) ............................................................................ 19
4.3.3
Database Module (DB).................................................................................. 19
4.3.4
Pattern generation (PG)................................................................................. 20
Implementation.......................................................................................................... 21 5.1
Application development using “Eclipse” ........................................................ 22
5.2
Serial Communication....................................................................................... 23
5.2.1
Distribution protocol ..................................................................................... 23
5.2.2
Serial communication library:....................................................................... 24
5.3
6
7
Functionalities of the modules .......................................................................... 19
GUI design ........................................................................................................ 31
5.3.1
GUI for Voting pad application .................................................................... 31
5.3.2
GUI for Smart Home Control application..................................................... 45
5.4
Database Implementation.................................................................................. 63
5.5
Web Interface .................................................................................................... 65
5.5.1
Web Server.................................................................................................... 65
5.5.2
PHP and Ajax ................................................................................................ 65
5.5.3
Remote Administration ................................................................................. 65
Applications, Enhancement and Limitations............................................................. 78 6.1
Immediate Applications .................................................................................... 79
6.2
Enhancements.................................................................................................... 79
6.3
Limitations ........................................................................................................ 80
6.4
Performance Issues............................................................................................ 80
Hardware Implementation......................................................................................... 81 7.1
Design of Sensor Node...................................................................................... 82
7.2
Design of the First Prototype ............................................................................ 84
7.2.1
Sensor Node .................................................................................................. 84
7.2.2
RS-232 to RS-485 Bridge ............................................................................. 88
7.2.3
Power Supply for the Network...................................................................... 89
7.3
Faults encountered with the First Prototype...................................................... 90
7.3.1
Faults in the RS-485 Network Wiring........................................................... 90
7.3.2
Faults in the Sensor Node Design ................................................................. 90 vi
7.3.3 7.4
Design of the Second Prototype ........................................................................ 92
7.4.1
Sensor Node .................................................................................................. 92
7.4.2
RS-232 to RS-485 Bridge ............................................................................. 95
7.4.3
Design of the Final Sensor Node................................................................. 100
7.5 8
Faults in the RS-232 to RS-485 Bridge Design ............................................ 91
Oscilloscope Traces......................................................................................... 103
The Elecrama Experience........................................................................................ 105
Appendix 1 - List Of References..................................................................................... 107 Appendix 2 - Data Flow Diagrams ................................................................................. 109 Appendix 3 - Table Of Figures ....................................................................................... 113 Appendix 4 - Index.......................................................................................................... 116
vii
1 General Overview
1
1.1 Introduction Technological advances in communications and electronics has enabled the development of low-cost, low power, multifunctional Sensor Nodes. These Sensor Nodes are capable of data collection, data processing and can communicate over long distances, leveraging the idea of sensor networks. Sensor networks have significantly improved over traditional sensors and have become an indispensable tool in various fields such as industry, entertainment, military, health, etc. A sensor network consists of a large number of Sensor Nodes that can be deployed either inside the measured object or very close to it. These nodes may be deployed in remote locations and thus allow for remote monitoring of various parameters. The Sensor Nodes are complete with onboard processors. Thus the nodes carry out simple calculations and transmit only the required and partially processed data. The above-described features enable sensor networks to be used for wide range of applications. In health, for example, sensor networks can be deployed to monitor and assist disabled patients. In military, the rapid deployment and fault tolerant characteristics of sensor networks make them a very promising sensing technique for military command and control. Other commercial applications include voting pads for game shows, home security, inventory management, monitoring product quality, monitoring disaster-prone areas. The Sensor Nodes are usually strategically placed in the sensor field. Each of these nodes has the capability to collect and route data back to the host monitoring system. Data are routed back using a multi-drop network. This network reduces the number of wires required to connect field devices to the host. Our multi-utility sensor network aims at satisfying the following criteria: 1. Cost effectiveness 2. Easy availability of components 3. High immunity to noise 4. Ease of operation, flexibility and user friendly GUI 5. Ease of reconfiguration for other applications 6. Scalability 7. Rudimentary built-in processing capability
2
1.2 Structure of the network
Fig 1-1 Network Topology The network consists of the following components: 1. RS-485 Bus 2. Sensor Nodes 3. RS-232 to RS-485 Bridge 4. Host computer
1.2.1 RS-485 Bus RS-485 Bus is a 3-wire interface that can be used to implement multi-drop networks. When a network needs to transfer small blocks of information over long distances, RS-485 is often the interface of choice. The network nodes can be PCs, microcontrollers, or any devices capable of asynchronous serial communication. Compared to Ethernet and other network interfaces, RS-485’s hardware and protocol requirements are simpler and cheaper. The RS-485 standard is flexible enough to provide a choice of drivers, receivers, and other components depending on the cable length, data rate, number of nodes, and the need to conserve power. Several vendors offer RS-485 transceivers with various combinations of features. Also, there are options for methods of terminating and biasing the line and controlling the driver enable inputs.
3
1.2.2 Sensor Nodes The Sensor Node is the main workhorse of the system. At its heart lies the ATmega8 microcontroller that is a high performance RISC controller with a built-in USART, Analog to Digital Converter (ADC) and Self Programming Capabilities. It can communicate with other nodes and the host over the RS-485 Bus. MAX485 level converter is used to convert the signals between TTL and RS-485 levels. The Sensor Node uses its ADC to sample data from its sensors and convert them to digital format. This collected sensor data is then processed by the ATmega8 microcontroller. The result of this processing is sent over the network to the host. The following sensors maybe used with the network: 1. Infrared/Capacitive/Inductive Proximity Sensor for counting objects on the Assembly Line 2. Single chip Temperature sensor or PT100 based Temperature sensor 3. Power supply monitoring ICs 4. Humidity Sensors 5. Gas Sensors (Carbon Monoxide, Nitrogen Oxide) 6. Calibrated Strain Gauge based Load Cells (For measuring weight) 7. Accelerometer (for measuring acceleration) 8. Tilt Switches (Mercury Switches) 9. Hall effect switch IC 10. Hall Effect Vane Switch 11. Opto-interrupters 12. LVDTs 13. Shaft Encoders 14. Reed Switches 15. Flame Sensors (UV Sensors) 16. Any other sensors which are available pre-calibrated or don’t require calibration
4
1.2.3 RS-232 to RS-485 Bridge It is used to connect the RS-485 Bus to the Host computer via the RS-232 communications ports. It consists of a MAX232 level converter, which converts RS232 signals from the computer to TTL levels. These TTL signals are further converted to RS-485 signals using the MAX485/DS75176 driver ICs. An AVR ATmega8 microcontroller is used to monitor the incoming and outgoing data from the Host computer and switches the MAX485 between the transmitting and receiving mode accordingly. Multiple RS-232 to RS-485 Bridges can be used at either end of the network to increase network reliability and fault tolerance. It means that the networks can withstand breaks in the RS-485 medium (twisted pair) by querying the nodes from multiple points on the network. This requires multiple RS-232 Ports on the Host computer.
1.2.4 Host computer The Host computer is the link between the network and the external world. It is a Windows based system with multiple RS-232 serial ports and it communicates with the RS-485 Network using the RS-232 to RS-485 Bridges. The Host computer needs a Java Runtime Environment (JRE) to run various network applications. The Host computer monitors the network and acquires the data from the Sensor Nodes using a well-defined protocol. It processes these data and stores them in the database. For the Home Monitoring application, it dynamically displays the current data being read from the sensors. The Voting Pad application records the votes cast by the users and displays a graph suggesting the statistics. The Host computer also provides data to the database server where all the records are maintained.
5
1.3 Project Divisions The project was divided in three modules and three teams worked in simultaneously on these modules.
1.3.1 Hardware Implementation The physical existence of the network itself is ensured by the hardware implementation. This includes designing the circuits and the layouts for the Sensor Nodes and the RS-232 to RS-485 Bridges. Various features considered while designing are status-LEDs, on board ISP programming, on board crystal, reset circuitry, etc. EMC design issues are considered, as high-speed data transfer is involved. The circuits and the layouts have been designed in Eagle 4.11, a wellknown CAD software. The necessary circuitries for the sensors are also developed.
1.3.2 Embedded software Implementation The focus of using embedded software is to develop the intelligence for the Sensor Nodes. The software development for the onboard AVR microcontrollers, which collect and process sensor data, is done using Embedded C Language. WinAVR 2005 is used to write programs and AVRStudio 4.11 is used to burn the programs on to the microcontrollers. Programming for applications is as varied as Industrial Process Monitoring, Home Monitoring and Voting Pads has been done. Communication between the Sensor Network and the Host Computer follows a selfdeveloped protocol.
1.3.3 Host software Implementation The host computer runs software for acquiring data from the network. The software running on the host computer is written in Java. Eclipse IDE was used during the creation of the software. The library used for implementing serial communications in Java was RX/TX. The database server runs MySQL server 5.0 and takes data from the Host computer. It provides this data to the Web Server. The database server handles all details of the data chronologically and is responsible for providing the latest data to the user. The Web server runs a PHP based application that is Ajax enabled. The PHP application takes the details from the database server and passes it on to the client machines in graphical format. Ajax is used to reduce the load on the Web server as new data is sent to the client at regular intervals to reduce bandwidth requirements. On receiving the data from the web server, the JavaScript at the client side updates the graphs and views in the browser. The PHP application is also capable to communicate with a java daemon on the host machine to directly control and communicate with the network.
6
2 Host Software Introduction
7
2.1 Problem definition The project aimed at building "Sensor Network Management Software" which runs on the host computer. This software accomplishes following tasks: 1. It lets the user define a flexible topology of the sensor network. The software allows reconfigure the sensor network topology dynamically, through a GUI wherein the network manager specifies details about the unique address of the device and its physical location. 2. The software model specifies the format of packets, which are exchanged between the Serial port of the host computer and RS232 to RS-485 Bridge. 3. The host computer continuously (or periodically) polls sensor PCBs for the data. This data on reception by host is saved into databases against individual sensors in order to create a Database. 4. This stored information is used to generate statistics and trends followed by of the sensed data. Software facilitates graphical representation of information gathered over varying period of time so as to study the patterns generated.
8
2.2 Need of "Sensor Network Management Software” The RS-485 specification meets the requirements for a truly multi-point communications network, and the standard specifies up to 32 drivers and 32 receivers on a single bus over a distance up to 4000 feet without a repeater. Some RS-485 Transceivers modify the input impedance to allow up to 8-times more nodes to be connected to the same bus. As the above specification suggests, number of sensors are deployed over a long distance, which essentially need some central management. Depending on the application the number of sensors deployed and distance between them may vary. Following features entail the development of the software.
2.2.1 Data Acquisition As the data is collected from sensors across the network it is essential to monitor the variations in the reading. Host computer serves as data acquisition centre of the network. This data can also be used to study patterns of the data received.
2.2.2 Data Analysis The data which is collected from individual sensors should be analysed to study trends and patterns. For this reason the data received is plotted along timeline.
Scope of the project We describe what features are in the scope of the software 1. The "Sensor Network Management Software" is platform independent 2. User-friendly GUI that lets the user fix the topology of the network 3. Distribution protocol that governs handshake of signals and data transfer along the network 4. Facility to monitor on the screen, the data received by individual sensors all at a time or individually
9
3 Software Requirement Specification
10
3.1 Software Requirements 3.1.1 Hardware Requirements The following are the requirements from hardware: 1. An IBM Compatible PC with a serial (RS-232) port with standard input and output devices. A Pentium 166MHz or faster processor with a minimum of 75MB free disk space and a minimum of 32MB of RAM is recommended. 2. A sensor network is needed which should be capable of understanding the commands and messages from the host and should follow the Packet format specified by the host to communicate via the RS485 bus. 3. The sensor network should be compatible with the present hardware and equipment in the industry. 4. The sensor network should essentially have a RS-232 to RS-485 Bridge that connects the Serial (RS-232) port of the host to the RS-485 bus to which all components/nodes are connected through splitters. 5. The components on the network should be Atmel AVR microcontroller based and should have a boot loader within them in order to allow the host to reprogram them and reconfigure the network. 6. Each node in the network must be capable to recognize a command that is issued to it by the host and must reply back to the host within a specific timeout.
3.1.2 Software Requirements 1. Platform(s): Solaris SPARC, Solaris x86, JDS, Red Hat Linux, SUSE Linux, Windows 98, Windows ME, Windows 2000 (SP4+), Windows XP (SP1 SP2), Windows 2003 2. JRE version(s): 1.4.2_xx
11
3.1.3 User Interfaces Listed below are the requirements that the software GUI should possess 1. At any time, the software should show the overall status of the sensor network. 2. The user interfaces should be consistent and should follow a specific standard. 3. The user should be informed of all major activities that were performed by the software and minor details should be hidden from the user.
3.1.4 User Constraints The characteristics of the intended users of the Sensor network software are as follows: 1. The user should belong to the industry/home where the sensor network is deployed and should be aware of the working of that particular industry. 2. He should have an idea about the network topology and the geographical distribution of his industry. 3. The user must know how to use a computer and the peripherals attached to it. Essentially a common user would require using only the keyboard and mouse. 4. He should also have sound knowledge of the various hardware components in the network. 5. Given the source of error, the user must be able to relate to the errors possible with the particular component in the sensor network.
12
3.2 Use Case Diagram
Network Administrator
Fig 3-1 Use Case Diagram
13
4 System Design
14
4.1 Identifying modules of the system
Fig 4-1 Block diagram of the system Above figure shows a block diagram of system of Sensor Network Management Software for the sensor network. Host computer (HC) on the left represents a server connected to the sensor network. The Sensor Network (SN) on the right is made up of many sensor PCBs that are attached to RS-485 bus. The model is made up of 4 main modules: 1. User Interface (UI) 2. Distribution Protocol (DP) 3. Database Module (DB) 4. Pattern generation (PG)
15
User Interface
Pattern Generation
Distribution Protocol
Sensor Network
Database
Fig 4-2 Module Interaction Diagram
16
4.2 Description of modules and their interaction 4.2.1 User Interface (UI) The GUI denotes various sensors present along the network and their current status. Network administrator uses User interface to set the topology of the sensor network. While setting this topology user can enter the details such as node id, sensor id and the location of this sensor. This topology can be entered, updated and it can also be retrieved using the interface.
4.2.2 Distribution Protocol (DP) Distribution protocol governs the exchange of the data, Bootloader programs and software updates between host computer and the individual sensor PCBs. The "Sensor Network Management Software" works data acquisition mode. 4.2.2.1 Distribution Protocol in sensing mode In this mode, the host computer gathers data from sensor PCBs. The conceptual steps involved in this protocol can be listed as follows. 1. Host computer sends a message: “send the data”. This message is intended for single sensor 2. Sensor PCB sends the data to host computer. This polling method goes on in round-robin manner. 4.2.2.2 Format of the packet for data transfer Distribution protocol specifies the format of packets, which are exchanged between the Serial port of the host computer and RS-232 to RS-485 Bridge. It will be explained in details in further chapters.
4.2.3 Database Module (DB) Host computer serves as data acquisition centre. Three types of details are stored into database. 1. Network topology: Physical location of each PCB node, each sensor and its unique address is stored. 2. Acquired data: Data received from the sensor are logged.
17
3. Network topology related information: Various parameters of network topology, parameters needed for target selection and update planning are stored.
4.2.4 Pattern generation (PG) To study the trends and patterns of the data sensed by the sensors, the data acquired in the databases are plotted along the timeline. 4.2.4.1 Data Monitoring Plot As and when the data from the sensor is received it is plotted along the timeline. It enables the network administrator to monitor the variations in the data received. This plot is dynamic and changes while the Administrator is seeing it. The signals from different sensors are distinguished by using different colours. The administrator can select a particular sensor whose graph is to be examined. Scaling is performed to have a coarser or a finer look over the plots over time whereas by shifting, the plots for different time intervals can be observed together.
18
4.3 Functionalities of the modules 4.3.1 User Interface (UI) User Interface Module
Input Physical location of sensor, node PCB; Address of sensor; Bus connections
Process control
& Output Display network topology, display sensor status.
Verify address of sensor PCBs
4.3.2 Distribution Protocol (DP) Distribution Protocol Module
Input Software mode, Intended target address
Process control
& Output Messages for successful delivery, Error messages
Determine packet format, Verify delivery of packets
4.3.3 Database Module (DB) Database Module
Input Sensor details, Network topology
Process control
& Output
Access database, Store information, Retrieve information
Data retrieved is shown on GUI at host m/c or Remote
19
4.3.4 Pattern generation (PG) Pattern Generation Module
Input Name/id of sensor
Process control
& Output Graph, Interrupt
Access database, Plot graph, Threshold checking
20
5 Implementation
21
5.1 Application development using “Eclipse” The entire application is developed using Java. We have used “Eclipse” editor for this purpose. Eclipse is an open source community whose projects are focused on providing an extensible development platform and application frameworks for building software.
Fig 5-1 Screenshot of Eclipse Editor Eclipse has formed an independent open eco-system around royalty-free technology and a universal platform for tools integration. Eclipse based tools give developers freedom of choice in a multi-language, multi-platform, multi-vendor environment. Eclipse provides a plug-in based framework that makes it easier to create, integrate and utilize software tools, saving time and money. By collaborating and exploiting core integration technology, tool producers can leverage platform reuse and concentrate on core competencies to create new development technology. The Eclipse Platform is written in the Java language and comes with extensive plugin construction toolkits and examples.
22
5.2 Serial Communication 5.2.1 Distribution protocol Distribution protocol specifies the format of packets, which are exchanged between the Serial port of the host computer and RS-232 to RS-485 Bridge. The packets sent along the line have following fields. Synchronization Character Sender Id Receiver Id Data Length Sensor Id Actual Data 1. Synchronization Character: Synchronization Character indicates the start of the packet. In all our examples we treat “a” as the Synchronization Character. 2. Sender Id: Sender can be a node or the host machine. Host machine has been assigned id 0. Nodes along the network are given ids starting from 1 and thereon in increasing order. This id is unique. 3. Receiver Id: Receiver can be host machine or a node. Its id is taken as receiver id. 4. Data Length: Data length specifies the no data bytes that will follow. 5. Sensor Id: Various sensors are used in an array of application. These sensors are assigned alphabetical ids starting from “A”. Since a single node/PCB can support 8 sensors. “Node id, sensor id” becomes the primary key to address a particular sensor on a particular node. 6. Actual Data: Depending upon the type of packet and its sender, the content and length of data field varies.
23
Packets can be of three types namely: Query packet, Reset packet and Data packet. In query packet data field contains the value “Q” to indicate Querying action. In reset packet data field contains the value “R” to indicate Reset action. In data packet data field contains the value sent by the individual sensor/keypad to the host machine
5.2.2 Serial communication library: The sensor network is ultimately connected to the serial port of the host computer via RS-232 to RS-485 Bridge. Thus serial communication plays an important role in the entire project. As we had chosen Java as our programming language for the "Sensor Network Management Software", we were confronted with two choices i.e.: Java COM API 3.0 (Published by SUN) and RxTx 2.1 (open source), to use as a library for serial communication. But since the support for Windows OS was under development in the latest Java COM API, we resorted to the GNU RxTx 2.1 Library for enabling serial communication. To use RxTx library with Eclipse, RXTXcomm.jar file and dll files are to be copied to the lib directory of project and JAR file is now to be used in the build path of the project. Given below is a program, which once included in the project package allows creating an object for serial communication.
// SerialClass.Java package kbc; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class SerialClass { private static SerialPort serialPort = null; private static InputStream in = null; private static OutputStream out = null; boolean valueSet=false;
24
int value = -1; /** * CONSTRUCTOR - sets up the serial port connection */ SerialClass() throws IOException{ // TODO Auto-generated method stub //Open the serial port serialPort = getSerialConnection("COM1", 115200); //Get a class which handles reading in = serialPort.getInputStream(); //Get a class which handles writing out = serialPort.getOutputStream(); } private static SerialPort getSerialConnection(String comPortNumber, int portSpeed) throws IOException { try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(comPortNumber); SerialPort serialPort = (SerialPort) portId.open("AppositeAgentSerial", 2000); serialPort.setSerialPortParams(portSpeed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); return serialPort; } catch (Exception e) { throw new IOException("Error opening port " + comPortNumber + ": " + e.getMessage()); } } public char receive()throws IOException{ int valueRead= in.read(); return ((char) valueRead); } public void send(String x)throws IOException{ byte data[]= x.getBytes(); out.write(data); out.flush(); } synchronized void put(int n){ if (valueSet) try{ wait(); }catch(InterruptedException e){ System.out.println ("Interrupted Exception caught"+e.getMessage()); } this.value=n; valueSet=true; System.out.println("Put : "+n); notify(); // test later for notifyAll }
25
synchronized int get(){ if (!valueSet) try{ wait(); }catch(InterruptedException e){ System.out.println("Interrupted Exception caught"+e.getMessage()); } System.out.println("Got : " + value); valueSet=false; notify(); // test later for notifyAll return value; } public void close(){ //close the serial port serialPort.close(); } }
To improve the reliability of data two serial ports of the host computer can be used simultaneously. So that in the first round polling is done using first serial port and in the second round polling is done in reverse direction using another serial port .In second round redundant data are not logged. Second round only ensures that there is no data loss in case of link failure.
26
Given below are two programs, which once included in the project package allow to create objects for serial communication using individual serial ports.
//SerialClass1.Java package kbc; import import import import
gnu.io.CommPortIdentifier; gnu.io.SerialPort; java.io.IOException; java.io.InputStream;
import java.io.OutputStream; public class SerialClass1{ private static SerialPort serialPort = null; private static InputStream in = null; private static OutputStream out = null; boolean valueSet=false; int value = -1;
//
/** * CONSTRUCTOR - sets up the serial port connection */ SerialClass1() throws IOException{ // TODO Auto-generated method stub Open the serial port serialPort = getSerialConnection("COM1", 115200); //Get a class which handles reading in = serialPort.getInputStream(); //Get a class which handles writing out = serialPort.getOutputStream(); }
private static SerialPort getSerialConnection(String comPortNumber, int portSpeed) throws IOException { try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(comPortNumber); SerialPort serialPort = (SerialPort) portId.open("AppositeAgentSerial", 2000); serialPort.setSerialPortParams(portSpeed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); return serialPort; } catch (Exception e) { throw new IOException("Error opening port " + comPortNumber + ": " + e.getMessage()); }
27
} public char receive()throws IOException{ int valueRead= in.read(); return ((char) valueRead); } public void send(String x)throws IOException{ byte data[]= x.getBytes(); out.write(data); out.flush();
} synchronized void put(int n){ if (valueSet) try{ wait(); }catch(InterruptedException e){ System.out.println("Interrupted Exception caught"+e.getMessage()); } this.value=n; valueSet=true; System.out.println("Put : "+n); notify(); // test later for notifyAll } synchronized int get(){ if (!valueSet) try{ wait(); }catch(InterruptedException e){ System.out.println("Interrupted Exception caught"+e.getMessage()); } System.out.println("Got : " + value); valueSet=false; notify(); // test later for notifyAll return value; } public void close(){ // Do not forget to close the serial port serialPort.close(); } }
28
//SerialClass2.Java package kbc;
import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class SerialClass2{ private static SerialPort serialPort = null; private static InputStream in = null; private static OutputStream out = null; boolean valueSet=false; int value = -1;
//
/** * CONSTRUCTOR - sets up the serial port connection */ SerialClass2() throws IOException{ // TODO Auto-generated method stub Open the serial port serialPort = getSerialConnection("COM2", 115200); //Get a class which handles reading in = serialPort.getInputStream(); //Get a class which handles writing out = serialPort.getOutputStream(); }
private static SerialPort getSerialConnection(String comPortNumber, int portSpeed) throws IOException { try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(comPortNumber); SerialPort serialPort = (SerialPort) portId.open("AppositeAgentSerial", 2000); serialPort.setSerialPortParams(portSpeed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); return serialPort; } catch (Exception e) { throw new IOException("Error opening port " + comPortNumber + ": " + e.getMessage()); } } public char receive()throws IOException{ int valueRead= in.read(); return ((char) valueRead); } public void send(String x)throws IOException{
29
byte data[]= x.getBytes(); out.write(data); out.flush();
} synchronized void put(int n){ if (valueSet) try{ wait(); }catch(InterruptedException e){ System.out.println("Interrupted Exception caught"+e.getMessage()); } this.value=n; valueSet=true; System.out.println("Put : "+n); notify(); // test later for notifyAll } synchronized int get(){ if (!valueSet) try{ wait(); }catch(InterruptedException e){ System.out.println("Interrupted Exception caught"+e.getMessage()); } System.out.println("Got : " + value); valueSet=false; notify(); // test later for notifyAll return value; }
//
public void close(){ Do not forget to close the serial port serialPort.close(); }
}
30
5.3 GUI design We are displaying two different applications of Multi Utility Sensor Network, that is: Voting pads for Games/Quizzes and Smart Home Control application. Graphical User Interface of “ Sensor Network Management Software” forms the front-end with which the user deals.
5.3.1 GUI for Voting pad application In the voting pad applications a question along with four options is displayed on the GUI .The voting pads along the network form the nodes of the network on which options are provided. Once the answers are registered they are queried using a button provided onto GUI. There is one graph option provided onto GUI. When Host acquires all the answers, a graph can be plotted to display the percentage voting for individual options. Answers can be reset before displaying next question onto the terminal. Given below is the code for GUI design o f voting pads applications followed by its screenshot.
// KBC3.Java package kbc; import java.awt.Frame; import java.awt.GridLayout; import import import import import import import import import import import import import import import import
org.eclipse.swt.SWT; org.eclipse.swt.awt.SWT_AWT; org.eclipse.swt.custom.CLabel; org.eclipse.swt.graphics.Font; org.eclipse.swt.layout.FillLayout; org.eclipse.swt.widgets.Button; org.eclipse.swt.widgets.Composite; org.eclipse.swt.widgets.Display; org.eclipse.swt.widgets.Label; org.eclipse.swt.widgets.Shell; org.eclipse.swt.widgets.Text; org.jfree.chart.ChartFactory; org.jfree.chart.ChartPanel; org.jfree.chart.JFreeChart; org.jfree.chart.plot.PlotOrientation; org.jfree.data.category.DefaultCategoryDataset;
public class KBC3 { private Shell sShell = null; // @jve:decl-index=0:visualconstraint="18,33" private Button button1 = null; private Button buttonChart = null;
31
SerialClass sc ; //BarChart br; int i,CA,CB,CC,CD; static int x=0; private String question[]={"Which is the densly populated state in India?","Who was the first Indian Miss World ?"}; private String A[]={"Uttar Pradesh","Diana Hayden"}; private String B[]={"Maharashtra","Rita Faria"}; private String C[]={"West Bengal","Aishwarya Rai"}; private String D[]={"Gujarat","Priyanka Chopra"};
private Text textAreaReply = null; private Button buttonR1 = null; private Composite compositeChart = null; private Label label1 = null; private Label label4 = null; private Label label2 = null; private Label label3 = null; private Text text1 = null; private Text text2 = null; private Text text3 = null; private Text text4 = null; private Text text5 = null; private Button buttonQ = null; /** * This method initializes compositeChart * */ private void createCompositeChart() { compositeChart = new Composite(sShell, SWT.EMBEDDED); compositeChart.setLayout(new FillLayout()); compositeChart.setBounds(new org.eclipse.swt.graphics.Rectangle(14,357,508,253)); } public static void main(String[] args) { Display display = Display.getDefault(); KBC3 thisClass = new KBC3(); thisClass.createSShell(); thisClass.sShell.open(); try { thisClass.sc = new SerialClass(); }catch(Exception e) { System.out.println("Exception"+e.getMessage()); } while (!thisClass.sShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); thisClass.sc.close();
32
}
public void generateChart(int CA,int CB,int CC,int CD){ Create the JFreeChart data DefaultCategoryDataset dataset = new DefaultCategoryDataset(); System.out.println(CA+""+ CB+""+ CC+ ""+ CD); //
dataset.clear(); dataset.setValue(100*CA/(CA+CB+CC+CD), dataset.setValue(100*CB/(CA+CB+CC+CD), dataset.setValue(100*CC/(CA+CB+CC+CD), dataset.setValue(100*CD/(CA+CB+CC+CD),
"Options", "Options", "Options", "Options",
"A"); "B"); "C"); "D");
// Create the actuall JFreeChart chart JFreeChart chart = ChartFactory.createBarChart3D("Audience' Poll", "Options", "Percentage ", dataset, PlotOrientation.VERTICAL, true, false, false); // grab a new AWT frame from our shell Frame chartFrame = SWT_AWT.new_Frame(compositeChart); // set the layout of our frame to a GridLayout so the chart will // automatically fill the entire area chartFrame.setLayout(new GridLayout()); ChartPanel cp = new ChartPanel(chart); chartFrame.add(cp); } /** * This method initializes sShell */ private void createSShell() { sShell = new Shell(); sShell.setText("Voting Pad Application"); sShell.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 8, SWT.NORMAL)); sShell.setSize(new org.eclipse.swt.graphics.Point(581,644)); button1 = new Button(sShell, SWT.NONE); button1.setBounds(new org.eclipse.swt.graphics.Rectangle(417,211,104,35)); button1.setText("QUERY"); button1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { CA=CB=CC=CD=0; for(int j=1;j<=9;j++) {
33
System.out.print("\nQuery "+j+" ; Received : "); // TODO Auto-generated Event stub widgetSelected() try {
sc.send("b");
sc.send("a0"+j+"2KQ");}catch(Exception e1) {System.out.println("Exception caught"+e1.getMessage());} char received = '?'; try{ for(i=0;i<10;i++) { received = sc.receive(); if(received=='A' ||received=='B' ||received=='C' ||received=='D'||received=='N') { System.out.print(received); textAreaReply.setText(textAreaReply.getText()+System.getProperty("lin e.separator")+"Received" + received +" from Node #"+j); //String myString = new Character(received).toString(); //label1.setText(myString); if(received=='A') CA++; if(received=='B') CB++; if(received=='C') CC++; if(received=='D') CD++; for(i=0;i<65535;i++); break; } } }catch(Exception e2) {System.out.println("Exception caught"+e2.getMessage());} } } }); buttonChart = new Button(sShell, SWT.NONE); buttonChart.setBounds(new org.eclipse.swt.graphics.Rectangle(416,305,104,40)); buttonChart.setText("Generate Chart"); textAreaReply = new Text(sShell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); textAreaReply.setBounds(new org.eclipse.swt.graphics.Rectangle(12,211,378,124)); buttonR1 = new Button(sShell, SWT.NONE); buttonR1.setBounds(new org.eclipse.swt.graphics.Rectangle(416,258,104,36)); buttonR1.setText("RESET"); buttonR1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
34
//compositeChart = new Composite(sShell, SWT.NONE); for(int k=1;k<=9;k++) { System.out.println("RESET "+k); // TODO Autogenerated Event stub widgetSelected() try{ sc.send("ba0"+k+"2KR");}catch(Exception e1){ System.out.println("Exception caught"+e1.getMessage()); textAreaReply.setText(textAreaReply.getText()+System.getPropert y("line.separator")+" Node #"+k+"Reset"); } } }}); createCompositeChart(); label1 = new Label(sShell, SWT.CENTER | SWT.BORDER); label1.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); label1.setLocation(new org.eclipse.swt.graphics.Point(93,87)); label1.setSize(new org.eclipse.swt.graphics.Point(40,40)); label1.setText("A"); label4 = new Label(sShell, SWT.CENTER | SWT.BORDER); label4.setText("D"); label4.setLocation(new org.eclipse.swt.graphics.Point(306,142)); label4.setSize(new org.eclipse.swt.graphics.Point(40,40)); label4.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); label2 = new Label(sShell, SWT.CENTER | SWT.BORDER); label2.setText("B"); label2.setLocation(new org.eclipse.swt.graphics.Point(305,88)); label2.setSize(new org.eclipse.swt.graphics.Point(40,40)); label2.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); label3 = new Label(sShell, SWT.CENTER | SWT.BORDER); label3.setText("C"); label3.setLocation(new org.eclipse.swt.graphics.Point(94,141)); label3.setSize(new org.eclipse.swt.graphics.Point(40,40)); label3.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); text1 = new Text(sShell, SWT.BORDER); text1.setBounds(new org.eclipse.swt.graphics.Rectangle(150,88,136,41)); text1.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text2 = new Text(sShell, SWT.BORDER); text2.setBounds(new org.eclipse.swt.graphics.Rectangle(363,90,121,41));
35
text2.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text3 = new Text(sShell, SWT.BORDER); text3.setBounds(new org.eclipse.swt.graphics.Rectangle(150,144,138,37)); text3.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text4 = new Text(sShell, SWT.BORDER); text4.setBounds(new org.eclipse.swt.graphics.Rectangle(362,142,124,38)); text4.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text5 = new Text(sShell, SWT.BORDER); text5.setLocation(new org.eclipse.swt.graphics.Point(91,31)); text5.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text5.setSize(new org.eclipse.swt.graphics.Point(470,35)); buttonQ = new Button(sShell, SWT.NONE); buttonQ.setBounds(new org.eclipse.swt.graphics.Rectangle(12,30,63,35)); buttonQ.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 10, SWT.NORMAL)); buttonQ.setText("Question"); buttonQ.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() int m=(x++)%2; text5.setText(question[m]); text1.setText(A[m]); text2.setText(B[m]); text3.setText(C[m]); text4.setText(D[m]); } }); buttonChart.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() compositeChart.dispose(); createCompositeChart(); generateChart(CA,CB,CC,CD); } }); } }
36
Fig 5-2 Screenshot of KBC The GUI can be modified to implement the management software using two serial ports. Following is the code for modified GUI of voting pad application. Although underlying code changes as it is depicted below, the external appearance of the GUI remains the same as it is displayed in Fig 5.2
37
// KBC4.Java package kbc; import java.awt.Frame; import java.awt.GridLayout; import import import import import import import import import import import import import import import import
org.eclipse.swt.SWT; org.eclipse.swt.awt.SWT_AWT; org.eclipse.swt.custom.CLabel; org.eclipse.swt.graphics.Font; org.eclipse.swt.layout.FillLayout; org.eclipse.swt.widgets.Button; org.eclipse.swt.widgets.Composite; org.eclipse.swt.widgets.Display; org.eclipse.swt.widgets.Label; org.eclipse.swt.widgets.Shell; org.eclipse.swt.widgets.Text; org.jfree.chart.ChartFactory; org.jfree.chart.ChartPanel; org.jfree.chart.JFreeChart; org.jfree.chart.plot.PlotOrientation; org.jfree.data.category.DefaultCategoryDataset;
public class KBC4 { private Shell sShell = null; // @jve:decl-index=0:visualconstraint="18,33" private Button button1 = null; private Button buttonChart = null; SerialClass1 sc1 ; SerialClass2 sc2; //BarChart br; int i,CA,CB,CC,CD; static int status[]=new int[9]; static int x=0; private String question[]={"Which is the densly populated state in India?","Who was the first Indian Miss World ?"}; private String A[]={"Uttar Pradesh","Diana Hayden"}; private String B[]={"Maharashtra","Rita Faria"}; private String C[]={"West Bengal","Aishwarya Rai"}; private String D[]={"Gujarat","Priyanka Chopra"};
private private private private private private private private private private private private
Text textAreaReply = null; Button buttonR1 = null; Composite compositeChart = null; Label label1 = null; Label label4 = null; Label label2 = null; Label label3 = null; Text text1 = null; Text text2 = null; Text text3 = null; Text text4 = null; Text text5 = null;
38
private Button buttonQ = null; /** * This method initializes compositeChart * */ private void createCompositeChart() { compositeChart = new Composite(sShell, SWT.EMBEDDED); compositeChart.setLayout(new FillLayout()); compositeChart.setBounds(new org.eclipse.swt.graphics.Rectangle(14,357,508,253)); } public static void main(String[] args) { Display display = Display.getDefault(); KBC4 thisClass = new KBC4(); thisClass.createSShell(); thisClass.sShell.open(); try { thisClass.sc1 = new SerialClass1(); thisClass.sc2 = new SerialClass2(); }catch(Exception e) { System.out.println("Exception"+e.getMessage()); } for(int i=0;i<9;i++) status[i]=0; while (!thisClass.sShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); thisClass.sc1.close(); thisClass.sc2.close(); }
public void generateChart(int CA,int CB,int CC,int CD){ Create the JFreeChart data DefaultCategoryDataset dataset = new DefaultCategoryDataset(); System.out.println(CA+""+ CB+""+ CC+ ""+ CD); //
dataset.clear(); dataset.setValue(100*CA/(CA+CB+CC+CD), dataset.setValue(100*CB/(CA+CB+CC+CD), dataset.setValue(100*CC/(CA+CB+CC+CD), dataset.setValue(100*CD/(CA+CB+CC+CD),
"Options", "Options", "Options", "Options",
"A"); "B"); "C"); "D");
// Create the actuall JFreeChart chart JFreeChart chart = ChartFactory.createBarChart3D("Audience' Poll",
39
"Options", "Percentage ", dataset, PlotOrientation.VERTICAL, true, false, false); // grab a new AWT frame from our shell Frame chartFrame = SWT_AWT.new_Frame(compositeChart); // set the layout of our frame to a GridLayout so the chart will // automatically fill the entire area chartFrame.setLayout(new GridLayout()); ChartPanel cp = new ChartPanel(chart); chartFrame.add(cp); } /** * This method initializes sShell */ private void createSShell() { sShell = new Shell(); sShell.setText("Voting Pad Application"); sShell.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 8, SWT.NORMAL)); sShell.setSize(new org.eclipse.swt.graphics.Point(581,644)); button1 = new Button(sShell, SWT.NONE); button1.setBounds(new org.eclipse.swt.graphics.Rectangle(417,211,104,35)); button1.setText("QUERY"); button1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { CA=CB=CC=CD=0; for(int j=1;j<=6;j++) { System.out.print("\nQuery "+j+" ; Received : "); // TODO Auto-generated Event stub widgetSelected() try { sc1.send("b"); sc1.send("a0"+j+"2KQ");}catch(Exception e1) {System.out.println("Exception caught"+e1.getMessage());} char received = '?'; try{ for(i=0;i<20;i++) { received = sc1.receive(); //System.out.println(received);
40
if(received=='A' ||received=='B' ||received=='C' ||received=='D'||received=='N') { System.out.print(received); textAreaReply.setText(textAreaReply.getText()+System.getProperty("lin e.separator")+"Received" + received +" from Node #"+j); //String myString = new Character(received).toString(); //label1.setText(myString); status[j-1]=1; if(received=='A') CA++; if(received=='B') CB++; if(received=='C') CC++; if(received=='D') CD++; for(i=0;i<65535;i++); break; } } }catch(Exception e2) {System.out.println("Exception caught"+e2.getMessage());} //sc1.close(); //sc2.close();
} //polling in reverse order. for(int j=6;j>=1;j--) { System.out.print("\nQuery "+j+" ; Received : "); // TODO Auto-generated Event stub widgetSelected() try { sc2.send("b"); sc2.send("a0"+j+"2KQ");}catch(Exception e1) {System.out.println("Exception caught"+e1.getMessage());} char received = '?'; try{ for(i=0;i<20;i++) { received = sc2.receive(); // System.out.println(received); if(received=='A' ||received=='B' ||received=='C' ||received=='D'||received=='N') { System.out.print(received); textAreaReply.setText(textAreaReply.getText()+System.getProperty("lin e.separator")+"Received" + received +" from Node #"+j);
41
//String myString = new Character(received).toString(); //label1.setText(myString); if(status[j-1]!=1) { if(received=='A') CA++; if(received=='B') CB++; if(received=='C') CC++; if(received=='D') CD++; for(i=0;i<65535;i++); break; } } } }catch(Exception e2) {System.out.println("Exception caught"+e2.getMessage());} } } } ); buttonChart = new Button(sShell, SWT.NONE); buttonChart.setBounds(new org.eclipse.swt.graphics.Rectangle(416,305,104,40)); buttonChart.setText("Generate Chart"); textAreaReply = new Text(sShell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); textAreaReply.setBounds(new org.eclipse.swt.graphics.Rectangle(12,211,378,124)); buttonR1 = new Button(sShell, SWT.NONE); buttonR1.setBounds(new org.eclipse.swt.graphics.Rectangle(416,258,104,36)); buttonR1.setText("RESET"); buttonR1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { //compositeChart = new Composite(sShell, SWT.NONE); for(int k=1;k<=6;k++) { System.out.println("RESET "+k); // TODO Autogenerated Event stub widgetSelected() try{for(int j=3;j>=1;j--) sc1.send("ba0"+k+"2KR"); } catch(Exception e1) { System.out.println("Exception caught"+e1.getMessage()); textAreaReply.setText(textAreaReply.getText()+System.getPropert y("line.separator")+" Node #"+k+"Reset"); }
42
} for(int k=6;k>=1;k--) { System.out.println("RESET "+k); // TODO Autogenerated Event stub widgetSelected() try{for(int j=3;j>=1;j--) sc2.send("ba0"+k+"2KR"); } catch(Exception e1) { System.out.println("Exception caught"+e1.getMessage()); textAreaReply.setText(textAreaReply.getText()+System.getPropert y("line.separator")+" Node #"+k+"Reset"); } } }}); createCompositeChart(); label1 = new Label(sShell, SWT.CENTER | SWT.BORDER); label1.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); label1.setLocation(new org.eclipse.swt.graphics.Point(93,87)); label1.setSize(new org.eclipse.swt.graphics.Point(40,40)); label1.setText("A"); label4 = new Label(sShell, SWT.CENTER | SWT.BORDER); label4.setText("D"); label4.setLocation(new org.eclipse.swt.graphics.Point(306,142)); label4.setSize(new org.eclipse.swt.graphics.Point(40,40)); label4.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); label2 = new Label(sShell, SWT.CENTER | SWT.BORDER); label2.setText("B"); label2.setLocation(new org.eclipse.swt.graphics.Point(305,88)); label2.setSize(new org.eclipse.swt.graphics.Point(40,40)); label2.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); label3 = new Label(sShell, SWT.CENTER | SWT.BORDER); label3.setText("C"); label3.setLocation(new org.eclipse.swt.graphics.Point(94,141)); label3.setSize(new org.eclipse.swt.graphics.Point(40,40)); label3.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.BOLD)); text1 = new Text(sShell, SWT.BORDER); text1.setBounds(new org.eclipse.swt.graphics.Rectangle(150,88,136,41)); text1.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text2 = new Text(sShell, SWT.BORDER);
43
text2.setBounds(new org.eclipse.swt.graphics.Rectangle(363,90,121,41)); text2.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text3 = new Text(sShell, SWT.BORDER); text3.setBounds(new org.eclipse.swt.graphics.Rectangle(150,144,138,37)); text3.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text4 = new Text(sShell, SWT.BORDER); text4.setBounds(new org.eclipse.swt.graphics.Rectangle(362,142,124,38)); text4.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text5 = new Text(sShell, SWT.BORDER); text5.setLocation(new org.eclipse.swt.graphics.Point(91,31)); text5.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 12, SWT.NORMAL)); text5.setSize(new org.eclipse.swt.graphics.Point(470,35)); buttonQ = new Button(sShell, SWT.NONE); buttonQ.setBounds(new org.eclipse.swt.graphics.Rectangle(12,30,63,35)); buttonQ.setFont(new Font(Display.getDefault(), "Microsoft Sans Serif", 10, SWT.NORMAL)); buttonQ.setText("Question"); buttonQ.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() int m=(x++)%2; text5.setText(question[m]); text1.setText(A[m]); text2.setText(B[m]); text3.setText(C[m]); text4.setText(D[m]); } }); buttonChart.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() compositeChart.dispose(); createCompositeChart(); generateChart(CA,CB,CC,CD); } }); } }
44
5.3.2 GUI for Smart Home Control application In Smart Home Control application, various sensors are deployed inside the home and the status of these sensors is queried from the central terminal. Status of individual sensor is displayed and updated on this GUI. Details related to the sensors such as their id, location (network topology) could be entered and updated by using this GUI. All such details are stored into database via GUI. Conversely, these details can be fetched from the database onto the GUI. Given below is the code for GUI design of Smart Home Control application followed by its screenshot.
//smarthomedb.Java package src; import import import import import import
java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement; java.sql.*;
import import import import import import import import import import
org.eclipse.swt.graphics.Point; org.eclipse.swt.widgets.Shell; org.eclipse.swt.widgets.Display; org.eclipse.swt.widgets.Label; org.eclipse.swt.SWT; org.eclipse.swt.graphics.Font; org.eclipse.swt.widgets.Button; org.eclipse.swt.widgets.Composite; org.eclipse.swt.widgets.Text; org.eclipse.swt.graphics.Color;
public class smarthomedb { private Shell sShell = null; // @jve:decl-index=0:visualconstraint="15,12" private Label label1 = null; private Label label2 = null; private Label label3 = null; private Label label4 = null; private Label label5 = null; private Label label6 = null; private Label label7 = null; private Label label8 = null; private Button radioButton1 = null; private Button radioButton2 = null; private Button radioButton3 = null; private Button radioButton4 = null; private Button radioButton5 = null; private Button radioButton6 = null; private Button button1 = null;
45
private Button button2 = null; private Button button3 = null; private Button button4 = null; private Label label11 = null; private Button checkBox1 = null; private Button checkBox2 = null; private Text text1 = null; private Text text2 = null; private Text text3 = null; private Text textArea1 = null; private Composite composite1 = null; private Composite compositeChart = null; /** * This method initializes composite1 * */ private void createComposite1() { composite1 = new Composite(sShell, SWT.NONE); composite1.setBounds(new org.eclipse.swt.graphics.Rectangle(336,-22,2,8)); } /** * This method initializes compositeChart * */ private void createCompositeChart() { compositeChart = new Composite(sShell, SWT.NONE); compositeChart.setBackground(new Color(Display.getCurrent(), 255, 255, 255)); compositeChart.setBounds(new org.eclipse.swt.graphics.Rectangle(9,320,635,150)); } private int muc_id,sensor_id, data,i_value; private float f_value; private char buffer[]= new char[12];
SerialClass sc ; private Label label9 = null; private Button radioButton7 = null; private Button radioButton8 = null; private Label label10 = null; public static void main(String[] args) { // TODO Auto-generated method stub /* Before this is run, be sure to set up the launch configuration (Arguments->VM Arguments) * for the correct SWT library path in order to run with the SWT dlls. * The dlls are located in the SWT plugin jar. * For example, on Windows the Eclipse SWT 3.1 plugin jar is: * installation_directory\plugins\org.eclipse.swt.win32_3.1.0.jar */
46
Display display = Display.getDefault(); smarthomedb thisClass = new smarthomedb(); thisClass.createSShell(); thisClass.sShell.open();
try { thisClass.sc = new SerialClass(); }catch(Exception e9) { System.out.println("Exception 9 "+e9.getMessage()); } //thisClass.poll(); while (!thisClass.sShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); thisClass.sc.close(); } /** * This method initializes sShell */ private void createSShell() { sShell = new Shell(); sShell.setText("Smart Home"); sShell.setToolTipText("Fetch"); sShell.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); sShell.setSize(new org.eclipse.swt.graphics.Point(663,515)); label1 = new Label(sShell, SWT.CENTER); label1.setBounds(new org.eclipse.swt.graphics.Rectangle(10,13,617,25)); label1.setFont(new Font(Display.getDefault(), "Tahoma", 12, SWT.BOLD)); label1.setText("Smart Home Control"); label2 = new Label(sShell, SWT.CENTER | SWT.BORDER); label2.setBounds(new org.eclipse.swt.graphics.Rectangle(492,45,149,25)); label2.setFont(new Font(Display.getDefault(), "Tahoma", 12, SWT.BOLD)); label2.setText("Home Status"); label3 = new Label(sShell, SWT.CENTER | SWT.BORDER); label3.setText("MotionIndicator"); label3.setSize(new org.eclipse.swt.graphics.Point(160,20)); label3.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label3.setLocation(new org.eclipse.swt.graphics.Point(493,81)); label4 = new Label(sShell, SWT.CENTER | SWT.BORDER); label4.setText("Door Open/Closed");
47
label4.setSize(new org.eclipse.swt.graphics.Point(160,20)); label4.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label4.setLocation(new org.eclipse.swt.graphics.Point(479,116)); label5 = new Label(sShell, SWT.CENTER | SWT.BORDER); label5.setText("LPG Detector"); label5.setSize(new org.eclipse.swt.graphics.Point(160,20)); label5.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label5.setLocation(new org.eclipse.swt.graphics.Point(485,142)); label6 = new Label(sShell, SWT.CENTER | SWT.BORDER); label6.setText("Temperature"); label6.setSize(new org.eclipse.swt.graphics.Point(160,20)); label6.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label6.setLocation(new org.eclipse.swt.graphics.Point(480,177)); label7 = new Label(sShell, SWT.CENTER | SWT.BORDER); label7.setText("Humidity"); label7.setSize(new org.eclipse.swt.graphics.Point(160,20)); label7.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label7.setLocation(new org.eclipse.swt.graphics.Point(479,205)); label8 = new Label(sShell, SWT.CENTER | SWT.BORDER); label8.setText("Light Sensor"); label8.setSize(new org.eclipse.swt.graphics.Point(160,20)); label8.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label8.setLocation(new org.eclipse.swt.graphics.Point(481,237)); radioButton1 = new Button(sShell, SWT.RADIO); radioButton1.setText("Motion Detector"); radioButton1.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton1.setLocation(new org.eclipse.swt.graphics.Point(7,72)); radioButton2 = new Button(sShell, SWT.RADIO); radioButton2.setText("Mercury Switch"); radioButton2.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton2.setLocation(new org.eclipse.swt.graphics.Point(5,94)); radioButton3 = new Button(sShell, SWT.RADIO); radioButton3.setText("GAS detector"); radioButton3.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton3.setLocation(new org.eclipse.swt.graphics.Point(2,118)); radioButton4 = new Button(sShell, SWT.RADIO); radioButton4.setText("Temperature Sensor");
48
radioButton4.setSize(new org.eclipse.swt.graphics.Point(119,20)); radioButton4.setLocation(new org.eclipse.swt.graphics.Point(3,139)); radioButton5 = new Button(sShell, SWT.RADIO); radioButton5.setText("Humidity Sensor"); radioButton5.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton5.setLocation(new org.eclipse.swt.graphics.Point(3,157)); radioButton6 = new Button(sShell, SWT.RADIO); radioButton6.setText("Light Sensor"); radioButton6.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton6.setLocation(new org.eclipse.swt.graphics.Point(6,174)); button1 = new Button(sShell, SWT.NONE); button1.setText("Enter"); button1.setSize(new org.eclipse.swt.graphics.Point(70,50)); button1.setLocation(new org.eclipse.swt.graphics.Point(131,92)); button1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { System.out.println("Could Not Load Driver"+ex.getMessage()); } try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost/musn?user=root");
String str1="insert into node(n_id,link_no) values ("+text1.getText()+",1)"; // String str1="insert into data(n_id,s_id,ts,val) values (1,68,now(),30)"; PreparedStatement stat=con.prepareStatement(str1); stat.executeUpdate(); textArea1.setText(textArea1.getText()+System.getProperty("line.separa tor")+"Node "+text1.getText()+" created "); stat.close(); con.close();
49
} catch (SQLException ex1) { // handle any errors System.out.println("SQLException: " + ex1.getMessage()); System.out.println("SQLState: " + ex1.getSQLState()); System.out.println("VendorError: " + ex1.getErrorCode()); } } }); button2 = new Button(sShell, SWT.NONE); button2.setText("Update"); button2.setSize(new org.eclipse.swt.graphics.Point(70,50)); button2.setLocation(new org.eclipse.swt.graphics.Point(216,90)); button2.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { System.out.println("Could Not Load Driver"+ex.getMessage()); } try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost/musn?user=root"); String s=new String(); String s2=new String();
if(radioButton1.getSelection()){s="65";s2="Motion Detector";} if(radioButton2.getSelection()){s="66";s2="Mercury Switch";} if(radioButton3.getSelection()){s="67";s2="Gas Detector";} if(radioButton4.getSelection()){s="68";s2="Temprature Sensor";} if(radioButton5.getSelection()){s="69";s2="Humidity Sensor";} if(radioButton6.getSelection()){s="70";s2="Light Sensor";} if(radioButton6.getSelection()){s="71";s2="Proximity Sensor";} if(radioButton8.getSelection()){s="72";s2="Smoke Detector";} String str1="insert into sensor(n_id,s_id,loc_x,loc_y) values ("+text1.getText()+","+s+","+text2.getText()+","+text3.getText()+")"; PreparedStatement stat=con.prepareStatement(str1); stat.executeUpdate();
50
textArea1.setText(textArea1.getText()+System.getProperty("line.separa tor")+s2+" added at node "+text1.getText()); stat.close(); con.close();
} catch (SQLException ex1) { // handle any errors System.out.println("SQLException: " + ex1.getMessage()); System.out.println("SQLState: " + ex1.getSQLState()); System.out.println("VendorError: " + ex1.getErrorCode()); } } }); button3 = new Button(sShell, SWT.NONE); button3.setText("Fetch"); button3.setSize(new org.eclipse.swt.graphics.Point(70,50)); button3.setLocation(new org.eclipse.swt.graphics.Point(130,151)); button3.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { System.out.println("Could Not Load Driver"+ex.getMessage()); } try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost/musn?user=root"); Statement stat=con.createStatement(); String s=new String(); String s2=new String(); String sql = "SELECT * FROM sensor"; ResultSet rs = stat.executeQuery(sql); if(rs!=null) textArea1.setText(textArea1.getText()+System.getProperty("line. separator")+"Current Topology is :"); textArea1.setText(textArea1.getText()+System.getProperty("line. separator")+"Node"+" "+"Sensor"+" "+"Co-ordinates");
51
while(rs.next()) { int n_id = rs.getInt("n_id"); int s_id = rs.getInt("s_id"); int loc_x = rs.getInt("loc_x"); int loc_y = rs.getInt("loc_y"); String s3=new String(); switch(s_id) { case 65: s3="Motion Detector"; break; case 66:s3="Mercury sensor"; break; case 67:s3="Gas detector"; break; case 68:s3="Temperature sensor"; break; case 69:s3="Humidity sensor"; break; case 70:s3="Light sensor"; break; case 71:s3="Proximity sensor"; break; case 72:s3="Smoke Detector"; break; } System.out.println(n_id+" loc_x+"
"+ s3+"
"+
"+ loc_y);
textArea1.setText(textArea1.getText()+System.getProperty("line.separa tor")+n_id+" "+ s3+" "+ loc_x+" "+ loc_y); } stat.close(); con.close();
} catch (SQLException ex1) { // handle any errors System.out.println("SQLException: " + ex1.getMessage()); System.out.println("SQLState: " + ex1.getSQLState()); System.out.println("VendorError: " + ex1.getErrorCode()); } } }); button4 = new Button(sShell, SWT.NONE); button4.setText("Chart"); button4.setLocation(new org.eclipse.swt.graphics.Point(213,153)); button4.setSize(new org.eclipse.swt.graphics.Point(70,50));
52
button4.setToolTipText("Chart"); button4.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() } }); label11 = new Label(sShell, SWT.CENTER); label11.setBounds(new org.eclipse.swt.graphics.Rectangle(83,49,232,25)); label11.setFont(new Font(Display.getDefault(), "Tahoma", 12, SWT.BOLD)); label11.setText("Topology Details"); checkBox1 = new Button(sShell, SWT.CHECK); checkBox1.setText("Node ID"); checkBox1.setSize(new org.eclipse.swt.graphics.Point(80,30)); checkBox1.setLocation(new org.eclipse.swt.graphics.Point(296,92)); checkBox2 = new Button(sShell, SWT.CHECK); checkBox2.setText("Location Set"); checkBox2.setSize(new org.eclipse.swt.graphics.Point(80,30)); checkBox2.setLocation(new org.eclipse.swt.graphics.Point(297,154)); text1 = new Text(sShell, SWT.BORDER); text1.setBounds(new org.eclipse.swt.graphics.Rectangle(380,95,65,30)); text2 = new Text(sShell, SWT.BORDER); text2.setLocation(new org.eclipse.swt.graphics.Point(383,154)); text2.setSize(new org.eclipse.swt.graphics.Point(30,30)); text3 = new Text(sShell, SWT.BORDER); text3.setLocation(new org.eclipse.swt.graphics.Point(427,156)); text3.setSize(new org.eclipse.swt.graphics.Point(30,30)); textArea1 = new Text(sShell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); textArea1.setBounds(new org.eclipse.swt.graphics.Rectangle(10,240,460,75)); createComposite1(); createCompositeChart(); label9 = new Label(sShell, SWT.CENTER | SWT.BORDER); label9.setText("No of Visitors"); label9.setSize(new org.eclipse.swt.graphics.Point(160,20)); label9.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label9.setLocation(new org.eclipse.swt.graphics.Point(485,268)); radioButton7 = new Button(sShell, SWT.RADIO); radioButton7.setText("Proximity Sensor"); radioButton7.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton7.setLocation(new org.eclipse.swt.graphics.Point(2,190));
53
radioButton8 = new Button(sShell, SWT.RADIO); radioButton8.setText("Smoke Detector"); radioButton8.setSize(new org.eclipse.swt.graphics.Point(100,20)); radioButton8.setLocation(new org.eclipse.swt.graphics.Point(6,217)); label10 = new Label(sShell, SWT.CENTER | SWT.BORDER); label10.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); label10.setLocation(new org.eclipse.swt.graphics.Point(486,297)); label10.setSize(new org.eclipse.swt.graphics.Point(160,20)); label10.setText("Smoke Presence"); } void extract(char buffer[]) { int j,i=0; while(buffer[i]!='a' && i<10)i++ ; if(i<=6) { j=i; muc_id=buffer[j+1]- 48; sensor_id=(buffer[j+4]); System.out.println("MUC ID:"+muc_id+" s id"+sensor_id+"&"+buffer[j+5]); int k= sensor_id; //motion, m.switch , lpg , light if(k==65||k==71||k==68||k==73) data=buffer[j+5]; //proximity if(k==72) data=(buffer[j+5]-48)*100+ (buffer[j+6]48)*10+(buffer[j+7]-48); //Humidity if(k==67) data=(buffer[j+5]-48)*10+ (buffer[j+6]-48); //Temp -LM35 if(k==70) { i_value=(int)buffer[j+5]; System.out.println("i_value = "+i_value); f_value= (float)116 * (float)i_value/(float)255; data=(int)f_value; System.out.println("Temp = "+data); } //smoke
54
if(k==69) data=buffer[j+5]; } else { muc_id=-1; sensor_id=-1; data=-1; } } void effect(int m,int s ,int data) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { System.out.println("Could Not Load Driver"+ex.getMessage()); } try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost/musn?user=root"); String str1="insert into data(n_id,s_id,ts,val) values ("+m+","+s+",now(),"+data+");"; //Statement stat = con.createStatement(); PreparedStatement stat=con.prepareStatement(str1); //System.out.println(str1); stat.executeUpdate(); stat.close(); con.close(); } catch (SQLException ex1) { // handle any errors System.out.println("SQLException: " + ex1.getMessage()); System.out.println("SQLState: " + ex1.getSQLState()); System.out.println("VendorError: " + ex1.getErrorCode()); } switch(sensor_id) { case 65: // light if (data==68) { try { label8.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label8.setText("Light ON"); //sc.send("a0"+m+"2AR"); } catch(Exception e4)
55
{System.out.println("Exception 4 caught"+e4.getMessage());} } if(data==78) { label8.setForeground(new Color(Display.getCurrent(), 0,128,0)); label8.setText("Light OFF"); } break; case 67: // Humidity if (data !=0) { try { label7.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label7.setText("Humidity ="+ data+"%"); } catch(Exception e3) {System.out.println("Exception 3 caught "+e3.getMessage());} } if(data==0) { label7.setForeground(new Color(Display.getCurrent(),
0,128,0)); label7.setText("Humidity
="+data+ "%"); } break; case 68: // LPG if (data==68) { try { label5.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label5.setText("
LPG
Leakage"); for(int j=1;j<=65535;j++); sc.send("a0"+m+"2DR"); } catch(Exception e1) {System.out.println("Exception 1 caught"+e1.getMessage());} }
56
if(data==78) { {
try
label5.setForeground(new Color(Display.getCurrent(), 0,128,0)); label5.setText(" no LPG Leakage"); for(int j=1;j<=65535;j++); sc.send("a0"+m+"2DR"); } catch(Exception e1) {System.out.println("Exception 1 caught"+e1.getMessage());} } break; case 69: // smoke sensor if (data==68) { try { label10.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label10.setText("Smoke Detected"); for(int o=1;o<=65535;o++) for(int p=1;p<=65535;p++) for(int q=1;q<=5;q++); sc.send("a0"+m+"2ER"); } catch(Exception e4) {System.out.println("Exception 4 caught"+e4.getMessage());} } if(data==78) { label10.setForeground(new Color(Display.getCurrent(), 0, 255, 0)); label10.setText("No Smoke"); } break; case 70: // Temperature sensor. try { label6.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label6.setText("Temperature ="+data+"°C"); } catch(Exception e6) {System.out.println("Exception 6 caught"+e6.getMessage());}
57
break; case 71: // M SWITCH. if (data==68) { try { label4.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label4.setText("Door Open"); } catch(Exception e2) {System.out.println("Exception 2 caught"+e2.getMessage());} } if(data==78) { label4.setForeground(new Color(Display.getCurrent(),
0,128,0)); label4.setText("Door
Closed"); } break; case 72: //proximity sensor try { if(data>=99) sc.send("a0"+m+"2HR");
label9.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label9.setText("COUNT="+data);
} catch(Exception e1) {System.out.println("Exception 1 caught"+e1.getMessage());} break; case 73: //Motion if (data==68) { try { label3.setForeground(new Color(Display.getCurrent(), 255, 0, 0)); label3.setText("Motion Detected");
58
//
System.out.println("muc id :"+m+"
sen id :"+ s); } catch(Exception e5) { System.out.println("Exception 5 caught"+e5.getMessage()); } } if(data==78) { label3.setForeground(new Color(Display.getCurrent(),
0,128,0)); label3.setText("No
motion"); } break; default: System.out.println("Wrong Sensor Id "); } } void poll() { int i,c; char j; for(;;) { for(i=1,j='A';j<='A';j++) { try { sc.send("a0"+i+"2"+j+"S"); System.out.println("a0"+i+"2"+j+"S"); // sc.send("ba022CS"); } catch(Exception e7) {System.out.println("Exception 7 caught"+e7.getMessage());} // for(int m=65535;m>=0;m--); char received = '?'; for(int k=0;k<12;k++) { try { received = sc.receive(); //System.out.println(received); buffer[k]=received; } catch(Exception e8) {System.out.println("Exception 8 caught "+e8.getMessage());}
59
} extract(buffer); effect(muc_id,sensor_id,data); } for(i=2,j='C';j<='D';j++) { try { sc.send("a0"+i+"2"+j+"S"); System.out.println("a0"+i+"2"+j+"S"); // sc.send("ba022CS"); } catch(Exception e7) {System.out.println("Exception 7 caught"+e7.getMessage());} // for(int m=65535;m>=0;m--); char received = '?'; for(int k=0;k<12;k++) { try { received = sc.receive(); //System.out.println(received); buffer[k]=received; } catch(Exception e8) {System.out.println("Exception 8 caught "+e8.getMessage());} } extract(buffer); effect(muc_id,sensor_id,data); } for(i=3,j='E';j<='F';j++) { try { sc.send("a0"+i+"2"+j+"S"); System.out.println("a0"+i+"2"+j+"S"); // sc.send("ba022CS"); } catch(Exception e7) {System.out.println("Exception 7 caught"+e7.getMessage());} // for(int m=65535;m>=0;m--); char received = '?'; for(int k=0;k<12;k++) { try { received = sc.receive(); //System.out.println(received); buffer[k]=received; } catch(Exception e8)
60
{System.out.println("Exception 8 caught "+e8.getMessage());} } extract(buffer); effect(muc_id,sensor_id,data); } for(i=4,j='G';j<='I';j++) { try { sc.send("a0"+i+"2"+j+"S"); System.out.println("a0"+i+"2"+j+"S"); // sc.send("ba022CS"); } catch(Exception e9) {System.out.println("Exception 9 caught"+e9.getMessage());} // for(int m=65535;m>=0;m--); char received = '?'; for(int k=0;k<12;k++) { try { received = sc.receive(); //System.out.println(received); buffer[k]=received; } catch(Exception e8) {System.out.println("Exception 8 caught "+e8.getMessage());} } extract(buffer); effect(muc_id,sensor_id,data); } } } }
61
Fig 5-3 Screenshot of Smart Home Control Interface
62
5.4 Database Implementation Database has been implemented only for Smart Home Control application using MySQL 5.0. The Database server and the Host computer can be the same or different in which case the database server can be moved to a safe remote location. Following are the details of the database implemented. Database: MUSN: Database schema: 1. link {link_no } 2. node {n_id, link_no} 3. sensor {n_id , s_id , loc_x, loc_y } 4. data { n_id , s_id ,ts , val}
63
Data definitions: (Schema design using MySQL)
CREATE TABLE link ( link_no INT UNSIGNED NOT NULL, PRIMARY KEY (link_no) ); CREATE TABLE node ( n_id INT UNSIGNED NOT NULL ,link_no INT UNSIGNED NOT NULL, PRIMARY KEY (n_id) , FOREIGN KEY (link_no) REFERENCES link(link_no) ); CREATE TABLE sensor ( n_id INT UNSIGNED NOT NULL , s_id INT UNSIGNED NOT NULL , FOREIGN KEY (n_id) REFERENCES node(n_id) loc_x int, loc_y int, PRIMARY KEY (n_id,s_id) ); CREATE TABLE data( n_id INT UNSIGNED NOT NULL , s_id INT UNSIGNED NOT NULL , ts timestamp, val int, FOREIGN KEY (n_id,s_id) REFERENCES sensor(n_id,s_id), PRIMARY KEY (n_id,s_id,ts)
);
64
5.5 Web Interface The Web interface to the Multi Utility Sensor Network is an extension to access the network from a remote computer. An authorized user performs functions like data acquisition, data analysis and remote control of the network parameters and the nodes. Various Components and Concepts of the web interface are discussed as follows:
5.5.1 Web Server A web server is required to host the web application that provides the functionalities required by the web interface. We have used the Apache 2 HTTP Server for our project. Apache is an open source web server and can be used freely. It supports a wide range of operating systems like Windows, Linux, BSD, and Mac OS etc. Although we have used Apache for hosting our web application, it runs flawlessly on other servers having PHP support as well.
5.5.2 PHP and Ajax PHP is a widely used general purpose scripting language that is especially suited for Web development and can be embedded into HTML. With PHP, we have incorporated all the required functionalities into our web application easily. PHP allows interaction with a large number of relational database management systems, including MySQL. PHP runs on most major operating systems, including Unix, Linux, Windows, and Mac OS X, and can interact with many major web servers. Thus we retain platform independence by choosing PHP as our scripting language. Asynchronous JavaScript And XML, or its acronym, Ajax is a Web development technique for creating interactive web applications. It allows us to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire Web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page's interactivity, speed, and usability. We have used Ajax so that client view of data is updated when the Browser receives new data. Updating the data is a better option as compared to reloading the page, since it gives a continuous effect that is required while plotting graphs. We have used the Sajax (Simple Ajax Toolkit) library for implementing our project. It is an open source tool designed to help websites to incorporate the Ajax framework into the web pages.
5.5.3 Remote Administration Remote Administration is an essential functionality required in the MUSN web application. An Authenticated user is allowed to fetch details from the network, analyse the data via charts and to change network parameters there by achieving control.
65
5.5.3.1 Authentication This is the basic need for the web application. A user must be authenticated in order to be allowed to access certain areas on the website. User management is handled by using sessions.
Fig 5-4 Screenshot of Authentication page
//connect.php
66
die("Can't connect to mysql."); }else{ if (!(mysql_select_db("$database",$db))) die("Can't connect to db."); } }
{
// start session session_start(); ?>
//auth.php Access Denied :: User Not Logged In
The resource that you are trying to access requires authentication.
Please login by clicking the login option on the menu.
"; echo "
"; echo "
If you are a valid user and have forgotten the password or are not able to access the pages due to some reasons, please contact the Administrator.
"; echo "
5.5.3.2 Status Check The status of sensor nodes can be checked from the web application. We can see all the sensors that are responding at a particular instance.