Location and Time Based Information Exchange System

234
____________________________________________________________ ____________ Master Thesis Location and Time Based Information Exchange System Master of Science (M.Sc) Study Program at ITU By H.M. Bilal Sarwar : [email protected] Nadeem Ahmad : [email protected] Shouket Iqbal : [email protected] Supervisors John Aasted Sørensen Kåre Jelling Kristoffersen

description

Location and Time Based Information Exchange System

Transcript of Location and Time Based Information Exchange System

Page 1: Location and Time Based Information Exchange System

________________________________________________________________________

Master Thesis

Location and Time Based Information Exchange System

Master of Science (M.Sc) Study Program at ITU

By

H.M. Bilal Sarwar : [email protected]

Nadeem Ahmad : [email protected]

Shouket Iqbal : [email protected]

Supervisors

John Aasted Sørensen

Kåre Jelling Kristoffersen

December 2003

Page 2: Location and Time Based Information Exchange System

________________________________________________________________________Preface.............................................................................................................................- 1 -Abstract...........................................................................................................................- 2 -1 Introduction..................................................................................................................- 3 -

1.1 Motivation.............................................................................................................- 3 -1.2 Problem Statement................................................................................................- 4 -1.3 Focus.....................................................................................................................- 5 -1.4 Literature...............................................................................................................- 6 -1.5 Methodology.........................................................................................................- 7 -1.6 Project Guide.........................................................................................................- 7 -

2 Problem Analyses........................................................................................................- 9 -2.1 Background...........................................................................................................- 9 -2.2 Related Work......................................................................................................- 10 -

2.2.1 PDCS Architecture.......................................................................................- 11 -2.2.2 PDCS Implementation.................................................................................- 11 -2.2.3 FPCS Architecture.......................................................................................- 11 -2.2.4 FPCS Implementation..................................................................................- 12 -

2.3 Example Scenarios..............................................................................................- 13 -2.3.1 Location Scenario........................................................................................- 13 -2.3.2 Time Scenario..............................................................................................- 14 -2.3.3 Time and Location Scenario........................................................................- 14 -2.3.4 Alert Zone Scenarios....................................................................................- 14 -

2.4 Cooperative Perspective of LTBIES...................................................................- 15 -2.4.1 Mobile Location Based Services Offered by LTBIES.................................- 15 -2.4.2 Usability in Different Cooperative Environments.......................................- 16 -2.4.3 Market Segments for LTBIES.....................................................................- 17 -

3 Positioning Technologies for Mobile Systems..........................................................- 20 -3.1 Outdoor Positioning Technology........................................................................- 21 -

3.1.1 Global Positioning System (GPS)................................................................- 21 -3.1.2 Global System for Mobile Communication (GSM).....................................- 24 -

3.2 Indoor Positioning Technology...........................................................................- 28 -3.2.1 Wireless Local Area Network (WLAN)......................................................- 29 -3.2.2 Ekahau Positioning Engine..........................................................................- 33 -

4 System Design............................................................................................................- 43 -4.1 Database Design..................................................................................................- 43 -

4.1.1 User Relation................................................................................................- 46 -4.1.2 Group Relation.............................................................................................- 46 -4.1.3 Message Relation.........................................................................................- 46 -4.1.4 Location Relation.........................................................................................- 46 -4.1.5 Group Member Relation..............................................................................- 47 -

4.2 Client Server Architecture..................................................................................- 47 -4.3 Positioning Server...............................................................................................- 49 -4.4 Simulated Position Server...................................................................................- 50 -4.5 Suggested Services..............................................................................................- 51 -

4.5.1 My Location.................................................................................................- 52 -4.5.2 Online Users.................................................................................................- 52 -4.5.3 Track Person................................................................................................- 53 -4.5.4 Message Services.........................................................................................- 53 -4.5.5 Alert Messages.............................................................................................- 53 -

Page 3: Location and Time Based Information Exchange System

________________________________________________________________________

4.6 Graphical User Interface Design.........................................................................- 54 -4.7 System Requirements..........................................................................................- 55 -

4.7.1 Hardware Requirements...............................................................................- 55 -4.7.2 Software Requirements................................................................................- 56 -

4.8 Tools and Techniques.........................................................................................- 56 -5 Implementation..........................................................................................................- 58 -

5.1 Software Design..................................................................................................- 58 -5.2 LTBIES Programming Model.............................................................................- 60 -

5.2.1 LTBIES Client to LTBIES Server Communication....................................- 61 -5.2.2 LTBIES Client to Positioning Server Communication................................- 61 -5.2.3 LTBIES Client and LTBIES Server to LTBIES Database Communication- 62 -5.2.4 Client Side Classes.......................................................................................- 63 -5.2.5 Server Side Classes......................................................................................- 64 -

5.3 Server Side Implementation................................................................................- 66 -5.3.1 Database Connectivity.................................................................................- 70 -

5.4 Client Side Implementation................................................................................- 73 -5.4.1 Exception Handling......................................................................................- 78 -5.4.2 Implementation of Map Component............................................................- 79 -

5.5 Thread Handling.................................................................................................- 81 -5.5.1 Issue in Multithreaded Programs.................................................................- 81 -5.5.2 Threads for Server........................................................................................- 81 -5.5.3 Threads for Client........................................................................................- 82 -5.5.4 Problem of Shared Resources......................................................................- 83 -

5.6 Database Implementation....................................................................................- 83 -5.7 Protocol Design...................................................................................................- 87 -

5.7.1 Protocols.......................................................................................................- 87 -5.7.2 LTBIES Protocol Structure..........................................................................- 87 -5.7.3 Client to Server Protocol..............................................................................- 87 -5.7.4 Server to Client Protocol..............................................................................- 89 -

6 Software Testing and Simulation...............................................................................- 90 -6.1 Software Testing.................................................................................................- 90 -

6.1.1 White Box Testing.......................................................................................- 90 -6.1.2 Black Box Testing........................................................................................- 92 -

6.2 Simulation...........................................................................................................- 94 -6.2.1 Simulation for LTBIES Application............................................................- 95 -6.2.2 Simulation for All Other LBS Application Developers...............................- 97 -

7 Conclusions................................................................................................................- 99 -Further Enhancements in LTBIES..............................................................................- 100 -Acknowledgements.....................................................................................................- 102 -References...................................................................................................................- 103 -Appendices..................................................................................................................- 106 -

A1 User Manual......................................................................................................- 106 -A2 Abbreviation List..............................................................................................- 108 -A3 UML Diagrams.................................................................................................- 109 -A4 Screen Shots......................................................................................................- 116 -A5 Database Tables................................................................................................- 123 -A6 Program Listing.................................................................................................- 125 -

Page 4: Location and Time Based Information Exchange System

________________________________________________________________________

Preface

This thesis has been written by a group of students at the IT University of

Copenhagen during the period of 1st of July 2003 to 8th of December 2003.

The idea of this system is conceived from the Global and Mobile applications,

mobile systems and distributed system courses.

To fulfil the requirements of the Master of Science (M.Sc) degree at the IT

University, we have to write a master thesis at end of our study program. So

this thesis is also a part of our final academic activity.

The evaluation of this thesis is based on 30 credit points.

H. M. Bilal Sarwar

Nadeem Ahmed

Shouket Iqbal

Copenhagen, December 2003

1

Page 5: Location and Time Based Information Exchange System

________________________________________________________________________

Abstract

With the recent and continuing advances in areas such as wireless

communications and positioning technologies, mobile, location-based

services are becoming possible. Such services deliver location-dependent

content to their users. This thesis “LTBIES” aims at the development of a

location and time based application for mobile users. The main goal of this

thesis is to investigate and then implement a location based application that

deals with a text message exchange for its clients at specific locations and at

specific time by using the existing positioning system at the ITU. This

application is able to get the position of a wireless device from the positioning

system. The application offers registration for new users or login for

registered users through the database for all clients. Clients who do not want

to become registered members are dealt as guest users. Clients have the

facility to put their messages into the database for delivery to a particular

person or group at specific location and at specific time. This application also

allows its end users to get information related to a particular domain based

on their current location, such as where my friends are? Strictly speaking, in

our application to handle desired information we are making these location

based services, richer and more target oriented by making them time bound.

This project is currently being carried out within the vicinity of the IT

University of Copenhagen, and tested at the ITU.

________________________________________________________________________2

Page 6: Location and Time Based Information Exchange System

________________________________________________________________________

1 Introduction

Location-awareness is a key to the success of future mobile applications. Information about a user’s current location enables a wide range of new services and can be used to increase the usability of existing applications deployed on resource-restricted small handheld devices like laptops, PDAs and mobile phones. In past the research in this area has mainly focused on outdoor geolocation systems. Examples for such systems include the Global Positioning System and positioning schemes deployed in cellular communication networks. These approaches however cannot provide accurate indoor geolocation and do not address the technical challenges of indoor environments. Hence, in the past few years there has been an increasing interest not only in research on indoor geolocation science and technology but also in developing many location based applications [Schmidt, 2003].

Generally locating users and terminals accurately within the buildings is new and important technology for different fields like commercial areas, customer service, military and public safety applications. Examples may include m-commerce1 applications to guide customers through huge departmental stores to aid policemen for surveillance, medical personals in hospitals and fire fighters within the buildings. Apart from such applications, which would not be possible without location information, many other applications can benefit from user context information [Schmidt, 2003], of which the geolocation is one of the important aspects. Knowledge about the user’s context in general and the user’s precise location in particular can greatly improve the usability of applications designed for mobile devices.

1.1 Motivation

Mobile devices have really revolutionized the communication and drastically affected the life style of the modern nomadic users. The inherent features of mobile devices are their high portability and personal nature. The voice capabilities of the mobile phones are currently augmented with data capabilities of increasing speed. The decreasing size of such mobile devices – laptops, mobile phones and PDAs – are converging and evolving into smart phones and communicators, which have allowed users to access Mobile

1 M-commerce is the abbreviation of mobile commerce.________________________________________________________________________

3

Page 7: Location and Time Based Information Exchange System

________________________________________________________________________Internet services and run different kind of applications at any time and at any place. Therefore, they are being used for storing and accessing information at

any time wherever the users go.

Thus the continuous availability of these devices and the emerging capability of the mobile terminals and/or the mobile network infrastructure to locate the mobile terminals in the indoor environment have motivated us with many others to develop new types of spatial and real-time services that are exactly

called Location-Based Services. According to some estimates in near future major part of the future Mobile Internet services are expected to be LBSs [Virrantaus, 2001].

1.2 Problem Statement

The main task is to design and implement an application, which should be able to provide an information exchange system on the basis of location and time. As opposed to ordinary gathering of information, in this application it is the interplay between the user’s profile and events governed by time and place, which will initiate the services. To use a simple description, it is the information that will find the right user at the right time instead of the person needing to search through information relevant in the current situation. In short; application should be able to answer the following questions:

Where is the user himself/herself located now?

Where are other members/friends?

How to notify its users with some special information on reaching at

that site.

How to make information exchange time bound?

For us the development of information services for individuals particularly about getting locations alone were not enough. Rather, the aim should be to satisfy the needs of users more precisely at least” right location” and” right on time”.

________________________________________________________________________4

Page 8: Location and Time Based Information Exchange System

________________________________________________________________________

1.3 Focus

Applications for a mobile environment certainly take advantage of contextual information, such as position, which itself is a very complex phenomena and needs special attention. Position can be discussed geographically, socially and relative to workflow model to offer greater services to the user. In this project, consideration was only a small part of the user’s context, specifically location and time. Knowledge of the user’s current location is used to provide more of the kind of services that we come to expect from a real or normal type of application. The architecture and features of the application will be described and then developed, only for indoor use on a given platform. The discussion will include the general research and technological issues that are important in developing context-aware (Location Based) applications in a mobile environment.

Obviously the general application domain which has driven the development of this project is indoor Location Based Services, which is quiet complicated and involves a lot of elements but we have found it necessary to be even more focused in one specific problem domain. That is the development of an application on a given platform (LaCoMoCo) [Schmidt, 2003].

Moreover Location Based Services can be classified by their functionality and utilization of location information. The basic class of the Location Based Services is location-based information services, utilizing the mobile user’s present location. In a simplest form it is a positioning service, informing the user about her/his present location (Where am I?). However, knowing only the coordinates is not very useful. Therefore this service is usually combined with a digital map associated to the user’s location. This service is a map service. A digital map can be only a basic map available on network without any more information. When the map is augmented with an access to some point-of-interest location information, the service type becomes a guiding service showing users on map. When the service includes capabilities to search information about real-world physical services, and perhaps a possibility to contact them, it becomes a mobile communication and information exchange service. The service may have features that support finding of the way to the specified destinations. This type of service is called navigation service. Location-based functional services can be distinguished from the information services [Schmidt, 2003]. Therefore, this application is mainly concerned with some functional services, which are using the mobile user’s present location. The example of asking a ________________________________________________________________________

5

Page 9: Location and Time Based Information Exchange System

________________________________________________________________________friend to pickup your books, which you have forgotten in the canteen by locating him in the canteen, can be a functional service. In this example present location of your friend belongs to this category. Alert messaging services are also an important group of functional services in the application. The next class of services in the application are location-aware services. Location-aware services are services where the user’s position or proximity to another object triggers some event or defines some condition. One example of such services is location-based marketing; where for example advertisement is send to the terminals approaching the ITU canteen.

The long-term research area is an application that knows where the user is, what he is looking at, can predict and answer questions he might pose, and provide the ability to interact with other people, organizational environment. Short-term goal is to implements a complete version of a kind of application on commercially available laptops.

1.4 Literature

We have taken courses like “Global and Mobile Applications”,” Distributed Systems” and “Mobile Systems” at the ITU. In these courses, we have studied positioning technologies GPS, GSM and WLAN, where WLAN is specifically being used for indoor positioning .At the ITU there is a positioning server called ”Ekahau” installed, which is based on WLAN indoor positioning technology.

The purpose of introducing students to these technologies was to give them a brief insight of problems and features of advanced and usable mobile LBS. When developing LBS, the constraints of a mobile computing environment have to be studied carefully. A general location-based service demands flexibility and scalability from the system architecture, so it is essential for application developers to read and understand existing system and platform. For this application development, abundance of detailed literature about positioning technologies motivated our choice of this area. While doing this we are following course compendium and the cases, which it has presented. More over, we are taking help from course web page and other online available recourses.

1.5 Methodology

________________________________________________________________________6

Page 10: Location and Time Based Information Exchange System

________________________________________________________________________In this study, we embedded use of available literatures as much as possible into observational work. Some small meetings had also been arranged with other groups to practically see their activities while working on their projects in which we were participants and observers. We spent several days observing the existing positioning system at the ITU. A focus of this work was the transfer of every piece of important information, such as how many access points are installed at the ITU or for example how LaCoMoCo is running on top of Ekahau. Mainly, some small meetings were held with the pioneers of LBS at the ITU. They were the members of LaCoMoCo team at the ITU.

On the basis of this observational work it was concluded that the system (LTBIES) will run on both a client machine (laptop/PDA) and a local serve in a Wireless Local Area Network (WLAN). The IT University of Copenhagen will be taken as a test environment, where the Ekahau positioning engine is running [Ekahau, 2002].We were intended to design a generic system that can be adjusted and deployed easily on different environments such as schools, Hospitals, Multi-storey shopping centres and huge complexes.

1.6 Project Guide

This section of the report is structured to give a brief introduction of the report’s chapters and their contents.

Chapter One concerns the motivation and focus for the development of Location Based Services. The goal is an adequate description of the phenomenon. Furthermore, the chapter describes the problem statement in detail to provide a solid thesis foundation.

Chapter Two describes the background of LBS at the ITU from an academic perspective. Original projects that have been done at the ITU are discussed and then described in the related work. The goal is a description and initialization of LBS at the ITU. In this Chapter problem has been described with the help of some scenarios for the justification of location based services applications for indoor environment. A brief cooperative perspective is presented at the end of this chapter to analyse the viability of the application in different organizations.

________________________________________________________________________7

Page 11: Location and Time Based Information Exchange System

________________________________________________________________________Chapter Three covers basic technologies of positioning system. It is divided into two parts, outdoor positioning technologies which give the brief description of Global Positioning System and Global System for Mobile Communication and the second part give the description of indoor positioning technology which covers basic principles of wireless local area network (IEEE 802.11b standard) and Ekahau positioning engine technique and technology.

Chapter Four covers components of system design which we developed to achieve the goals of this project.

Chapter Five tends to describe all aspects of implementation. This includes the actual steps for implementing the complete architecture. To give more meaning we have divided implementation of LTBIES application in to three main parts server side implementation, client side implementation and database implementation. Prior to these modules and core implementation software design along with definition of classes is given for better understanding.

Chapter Six covers the testing of software. For testing purposes, a simulation is developed. By using this simulation, the results are checked against particular location and specified time. This chapter also describe a general test bed (Simulated positioning server) for other location based services application developers.

Chapter seven gives the conclusions of thesis work and some ideas of possible future extension. It is followed by the list of references and appendices which include the programming code, abbreviations, database tables and diagrams

________________________________________________________________________8

Page 12: Location and Time Based Information Exchange System

________________________________________________________________________

2 Problem Analyses

2.1 Background

LBS satisfy user’s information needs at any given time relevant to their geographic position. This is a very practical technology solution to everyday problems that holds a truly exciting future. It is estimated that LBS revenue will grow in billions in near future according to an Allied Business Intelligence study [Bacastow, 2002]. This research effort strives to examine the viability and benefits of location-based services, to determine if its usefulness, convenience, and ability to satisfy user’s information needs at any given location and time will make it the next significant trend in mobile communication/computing on university campuses. Visitor information guides, event statistics, traffic patterns, weather forecasts, surveillance and local news are examples of useful information that could be delivered via LBS. Moreover, new smart devices are becoming available to better support LBS. In future research will be focused on applying this technology more and more almost every possible area including, personal security, public services, and commercial ventures.

The IT University of Copenhagen and Nokia are part of a group of European Universities and private enterprises that plan to create a European Laboratory for Context dependent Mobile Communication. To this end, an Expression of Interest has recently been submitted to the Commission of the European Union. The core group of partners in LaCoMoCo consists of the partners of Crossroads Copenhagen, a consortium of private and public companies including ITU and Nokia. The members of Crossroads Copenhagen started discussing possible project ideas in 1999. After many rounds of discussions, the members settled on the topic of Context-dependent Mobile Communication in early 2002, and then Crossroads Copenhagen was officially launched on May 2, 2002, by the Danish Minister for Science, Technology and Innovation. Crossroads Copenhagen has a board consisting of the CEOs of the partners and it has a professional secretariat, whose role is to help with the integration and administration of subprojects [Birkedal, 2002]. The purpose of these subprojects is to establish a standardised platform for distribution of individually relevant services and information on wireless

See www.crossroadscopenhagen.com/project_b.htm________________________________________________________________________

9

Page 13: Location and Time Based Information Exchange System

________________________________________________________________________terminals to persons who move around within a given geographic area [Birkedal, 2002].

2.2 Related Work

Many location-based applications have been developed during last couple of years at ITU. Some examples of such applications are, the “Position Dependent Communication systems” [Thomas, 2003], GIS in LBS [Schmidt, 2003] and” User Authentication and Information Exchange by Speech and Location Information in Mobile Systems” [El-Akehal, 2003] offer information to end users, taking into account their current location. Usually such systems come along with a general development framework, which allows a developer to create other location-aware applications. Several frameworks deal with location data and provide a platform for location-based application. At ITU most of the applications have been developed by using a platform called LaCoMoCo on top of Ekahu. A second example for location-based applications is context-aware messaging. Such systems trigger actions according to a specific location. ”User Authentication and Information Exchange by Speech and Location Information in Mobile Systems” is a system which links personal information to locations and generates events (e.g. voice messages), when a user moves to a certain location. “Position Dependent Communication systems” allows the users to find the shortest path till their destination by drawing the route on the map. “Geographic information systems in context of Location Based Services” (GIS in LBS) and spatial databases provide powerful mechanisms to store and retrieve location data [Petersen, 2003]. Such systems primarily concentrate on accessing large amounts of spatial data. These systems process context-aware and location-based information.

A detailed description of two main projects is presented here to give better understanding about their architecture and implementation along with their results.

________________________________________________________________________10

Page 14: Location and Time Based Information Exchange System

________________________________________________________________________2.2.1 PDCS Architecture

PDCS is a combination of Location Based Technologies and Speech Technologies (Java Speech API & IBM Via Voice Engine).The whole system is controlled by speech. PDCS provides the users with the shortest path from their physical location to a specific destination and can guide them along the path with synthetic voice till desired destination.

2.2.2 PDCS Implementation

The user’s physical location is being provided by the Position Server, the specific Destination will be provided by the User as an input. Actually PDCS is an Input Output system. Where Input is Speech consists of meaningful vocabulary (about the Destination).Output is a Map and Synthesized speech with information about direction towards the destination. The Output will be updated depending on the user’s position. The user will be notified at the final destination. As conclusion it is possible to build a Guided tour System using the available Location Based Technologies and Speech Technologies.

Results

The system is for indoor environment

The system can run in many areas like

Schools Hospitals Supermarkets

2.2.3 FPCS Architecture

The system is a combination of Location Based Technologies and Speech Technologies (recognizer built by using Java Language). The whole system will be controlled by speech. The system can also provide the users with tracking facility to track other registered users and find their locations. This user authentication by voice is used to filter the services for users. Moreover these provided services will depend on the user’s location.

2.2.4 FPCS Implementation

________________________________________________________________________11

Page 15: Location and Time Based Information Exchange System

________________________________________________________________________

The system can identify and authenticate the users by their voice. To fulfil this objective a speech recognizer using Hidden Markov Model has been built and implemented in java. The system is an Input Output system. Where input is speech (simple vocabulary for navigating) and output is a text message or the user’s location (map).This Output on the map can be updated depending on the user’s position.

Results

The system is for indoor environment

The system can run in many areas

Schools Hospitals Different Organizations

In these projects, substantial consideration has been given to database modelling and querying of moving objects (e.g., in [Lynge, 2003] and [El-Akehal, 2003]. In the context of location based services, continuous queries are of particular interest. Most systems consider only queries regarding the changes in user location. Extensive research on location-based services focuses on the technical challenges of interaction with the moving users or the spatiotemporal observation of moving objects. In most systems, the context is merely the user location measured at certain location that is, continuous queries, or profiles, only consider the user location. Additional contexts to consider would be, e.g., user interest, local time, and technical communication parameters. For example in the “Augmented Location-Based Services” (ALBS) [Schmidt, 2003], users are actively informed about general events along with location information, such as the opening hours of reception. This information is broadcasted to all user of the system, whether they are interested or not. Similarly, users are informed about all other available users.

We propose a Location and Time Based Information Exchange System (LTBIES), which allows the user to define complex conditions under which a reminder will be generated (e.g. time is "9:00" and location is "office1.49"). Conditions are stored in a database and linked to users. Whenever a condition is fulfilled, the system generates a message box. In our intended scenarios, however, we have to address issues such as connectivity across a network and mobility of clients, thus we have to use data distribution

________________________________________________________________________12

Page 16: Location and Time Based Information Exchange System

________________________________________________________________________concepts. We will also rely on existing platform LaCoMoCo, especially, for the relation between physical to semantic locations and the mapping of local sensor-data to global location information.

2.3 Example Scenarios

Developing and discussing scenarios is particularly fruitful approach for exploring the space of problems and solutions for them. Project’s main objective is to develop a reliable application, and to demonstrate how a consumer with a mobile terminal can access to a wider variety of services. In order to evaluate the benefits of services, some common scenarios must be clearly defined and presented. For this purpose, some example scenarios have been presented for the “LTBIES” project allowing a complete assessment of the project’s ambitious objective. The reason is that the technical contributions should build on a clear understanding of the existing application domain and its users. The following are some problem scenarios, which try to give a short view that, how this application would support its users. The scenarios will also illustrate some key features of the system.

2.3.1 Location Scenario

The first scenario is based on location service. While working at library suddenly a student realizes that he has forgotten his books in the canteen. He can not go back immediately but he might ask somebody at ITU to get the books by telling him the location of the books. A system is needed which could determine and guide one of his friends about the location of the books. System should be able to locate some of his friends nearby so that he can ask them to collect the books for him or by using the same system he can leave a message for his friend precisely at that location, and the message will be delivered to his friend at that particular location.

The Second scenario is also based on location service. A student who is working on a project remembers that one of his classmates has a book that might be helpful for his work. A system is needed which could locate and give the message to his friend about the book. System should be able to deliver the message immediately after he enters in the ITU or any predefined location for example library canteen or even a particular floor.

________________________________________________________________________13

Page 17: Location and Time Based Information Exchange System

________________________________________________________________________2.3.2 Time Scenario

Another scenario that we are going to present is based on time service. A teacher at ITU wants to have an urgent meeting with his fellow teacher but currently his colleague is giving a lecture. The lecture will end at 12 o’clock. A system is required which should be able to deliver that message exactly at 12 o’clock after the lecture.

2.3.3 Time and Location Scenario

This scenario is based on time and location service of the application. A student at ITU daily visits the canteen and especially eats there. He wants one of his friends to taste the fresh smoked fish, which is prepared today and will be served during lunch time that is from 12.00 o’clock to 1.00 o’clock. A system should be able to deliver that message between 12 o’clock to 1.00 o’clock only at canteen.

2.3.4 Alert Zone Scenarios

A group of students walking through the corridor having some noisy discussions without knowing that there is an on going exam in one of the rooms. A system is essential which should be able to deliver an alert message at that location “please be quiet”.

System administration has been informed that some computers in room 3.19 are not working properly and they want to fix them between 2 o’clock to 3 o’clock. Now a system is needed which should deliver this message in advance, moreover it should be able to inform everybody who reaches in front of the room and tries to enter in the room.

________________________________________________________________________14

Page 18: Location and Time Based Information Exchange System

________________________________________________________________________

2.4 Cooperative Perspective of LTBIES

There have been consecutive meetings of all groups throughout the thesis period. During those meetings constructive remarks have been made regularly by our supervisors, especially about all possible and positive improvements of the system, and what could be done to enhance the system usability. Among them one suggestion was about the cooperative analysis. This analysis was required to asses the future prospective of such systems more openly for different organizational environments.

To have a perspective overview of the system, it is important to take each service one by one and then test its viability for other organizations like hotels, schools and huge shopping centres.

2.4.1 Mobile Location Based Services Offered by LTBIES

There are two types of mobile location based services. First type is called location based services and the second type is called location dependent services. Location based services are the actual services which are seen by the user like navigation services. These services are provided by the service provider. Such services offers user interface for accessing the services. Where as location dependent services are that services, which are available depending on the users actual position. The service provider provides these services, when the user enters a certain area [Nokia, 2001].

LTBIES is capable of providing both types of services to its end users. Its ability to show all users on map is an example of location based services along with other services like information exchange depending on user’s location. Where as its ability to send a message precisely depending on user’s position at some specific point of time is a classic example of location dependent services.

LTBIES provide these types of mobile location based services to add value to services so that they can utilize user’s position information in a better way. LTBIES exploiting location element to make information more target oriented for users. In reality location information has no value in itself; it is just a parameter, which is extensively used for provisioning valuable services relevant to a user at a specific location at a specific point of time. LTBIES is

________________________________________________________________________15

Page 19: Location and Time Based Information Exchange System

________________________________________________________________________designed for end users. User can enjoy information exchange that is relevant in a particular location and at right moment. Personalized information is also available this information is about the user’s own location. User is allowed to make information more focused and of higher quality, when information is tailored according to the user’s defined location and time.

2.4.2 Usability in Different Cooperative Environments.

So far the development of LTBIES was motivated and discussed for IT University only, but LTBIES can be a good tool for providing mobile customers in different t cooperative environments with the right service at the right time and at the right location. Its ability to point out the location of a single individual on map has an obvious and vital value in the context of different organizations. Many organizations want to have a better cooperation within their employees, this feature can full fill the desire of better cooperation. To justify this discussion some scenarios from different organizations will be presented.

To make it for different environments a number of critical success factors were considered including technology and device adoption. Although technology and device adoption is ultimately driven by consumer’s demand, but the development of such an application must focus on consumers, because ease of use and ease of deployment will make it acceptable for different organizations. The first factor considered was device (laptop); it is obvious that this choice of device is in need of alternative. Laptop can not be considered as handy mobile terminal to carry around. Present implementation of LTBIES should be regarded as a prototype of a future system that can run on PDAs. Another focus was an optimised, user friendly and well-structured interface. LTBIES is using three different softwares (Photoshop, ImageReady and J2SE) to get user’s attention by providing an attractive and colourful interface.

LTBIES provide three major factors that boost information value to the end user. Many organizations can greatly benefited by these factors.

Personalized information

Time bound information exchange

Location bound information exchange

________________________________________________________________________16

Page 20: Location and Time Based Information Exchange System

________________________________________________________________________2.4.3 Market Segments for LTBIES

Mobile location based services are for two different environments, out door and indoor. LTBIES is particularly designed for indoor environment using WLAN (for details see chapter three). On the basis of its environment market segment should be identified. LTBIES tends to target organizations like Hotels, Hospitals, multi-storey huge shopping malls, Schools and big departmental organizations. To develop a clear understanding of LTBIES and its potential customers, Hotel has been selected to present some scenario-based evaluation.

Managerial Scenario

Consider a five star Hotel. Hotel is famous for its outstanding location and because of the different type of services that it provides. It has more than 200 rooms. For business community customers they have a conference room and some other attractions. They provide traditional services, like if hotel has anything new to offer their customers they usually distribute printed notes through the hotel staff. Often the hotel staff goes personally to customers to inform them. This arrangement has strong temporal elements too. Customers do not want to spend their time reading notes or trying to understand what is written. Customers seem to have a desire to spend time in activity rather than in preparing for activity. One thing is clear that the traditional ways like calling or knocking at the doors are not the good ways at all. Because exact mode situation and time schedule of customer is not known, he might be very tired or he might be having a nap or he might be busy doing something else. Therefore a system is needed which can locate customers and on the basis of their location give them right information at right time. For example if the system senses the location of a customer in front of dining hall it should give them the information about food and today’s offer. If it is dinnertime there is no need to publish Lunch offers at dinnertime.

Similarly hotel management can use this system to communicate and improve their cooperation. An emergency conference about new business policies is going to take place in conference hall. Hotel management could not inform about it earlier to their staff and customers. It was critical issue for the management because they have to do two major tasks. First one is to arrange the hall for the conference to make it perfectly ready and pass this information to their employees. The second is to locate all their customers who belong to business community and inform them about this conference.

________________________________________________________________________17

Page 21: Location and Time Based Information Exchange System

________________________________________________________________________Hotel management first want to locate their staff then they want to see where they are and what they are doing. They know their routine but some times some of them do not have anything to do, therefore they go into staff room to get some rest. They want to pass this information to customers without disturbing them, especially those who are in bar or out of any activity or logged on to the system or those who reaches in front of the conference hall. Using the proposed system Hotel management can inform its free staff while sensing their location in the staff room without bothering them in the position of their routine work.

By analysing and understanding the nature of managerial activities involved in different organizational works, it can be viewed that all these activities are highly collaborative, and involves a wide range of practices that can be better supported by deploying LBS. Factories can use it to inform their new employees or visitors on reaching at some danger zones by alert messaging. Hospitals could be a good market, where doctors, nurses and patients can use this; Nurses can use this system to make sure that the patient should take medicine at the right time if they are busy with other patients, by sending or making messages time bound.

Customer Scenario

This customer is a middle age man. He is a businessman from USA. He is in a business of import and export and as a result of the nature of his business he has to travel around the world to visit his business counterparts. He goes for meetings and spends time in different hotels. Major part of his business is in Europe. He visits constantly Copenhagen and stays in five star Hotel,

Now suppose if he has been given a location based services enabled device from hotel management. He had a business meeting with some business counterparts in the conference room but some how he is not feeling well so he decided to go to mini-bar but he leaves a message in the conference room for his friends which will be delivered to them when they enter in the conference hall. After a while he realizes that he might not be able to wait more that one hour in the bar therefore he can make his message time bound. During this period if the system senses those persons in that location system will deliver these messages, after that system will not deliver the message.

________________________________________________________________________18

Page 22: Location and Time Based Information Exchange System

________________________________________________________________________For customers point of view big supermarkets could be benefited from this application. Popping up messages and giving the customer information about special offers in a specific department.

Although the existing traditional systems are working good and both the customers and organizational managements are practicing it for a long time, the new Location Based Service can influence them all and they can have benefits out of these new technologies. In any important sense it seems that the new system will have strong impact on the coordination of their work.

________________________________________________________________________19

Page 23: Location and Time Based Information Exchange System

________________________________________________________________________

3 Positioning Technologies for Mobile Systems

The most important issue before going to develop a location based service application it is to decide which positioning technology is better and suit to get the location of mobile device. In this chapter the different positioning technologies, their advantages and disadvantages will be discussed. After going through the advantages and disadvantages of different positioning technologies it will be decided which technology best suits for this application development. Many location determination technologies have been employed to find out the location of a mobile device2. The positioning technology is used to deal with the physical position of the mobile device. Depending on the position of mobile device, the positioning technologies can be further grouped as

Outdoor positioning technology

Indoor positioning technology

There is no single method or technology that can operate effectively in all type of environments (e.g., indoor and open terrain) with sufficient accuracy. These technologies employed various media such as optical, acoustic or radio frequency (RF) and each has advantages in certain situations.

Outdoor positioning technology is based on the Global Positioning System (GPS). The GPS is satellite-based technology and is most widely used radio frequency system, providing global out door coverage. Since the satellite signals used in the GPS are prevented from entering by construction materials of the building, so the indoor positioning technology use another approach. Indoor positioning technology is based on wireless LAN (IEEE 802.11b standard). Wireless geolocation positioning system can be classified into the following two types [Nerguizian, 2001].

Network based geolocation

Handset based geolocation

In Network based geolocation, fixed stations receive signal from the mobile station and send information to a central station where the mobile

2 The mobile device may be laptop, PDA or mobile phone.________________________________________________________________________

20

Page 24: Location and Time Based Information Exchange System

________________________________________________________________________station’s location is computed [Nerguizian, 2001]. “It is referred to as Network based because the mobile network, in conjunction with network based position determination equipment is used to position the mobile device” [Turner, 2002].

In Handset based geolocation, a mobile station receives signals from the fixed stations and computes its own location. “It is referred to as Handset based because the handset itself is the primary means of positioning the user, although the network can be used to provide assistance in acquiring the mobile device and/or making position estimate determinations based on measurement data and handset based position determination algorithm” [Turner, 2002].

3.1 Outdoor Positioning Technology

In this section two most common outdoor positioning systems which are currently used almost every where in the world, will be discussed. One of them is the global positioning system, which is a satellite based technology and is most widely used radio frequency system, providing the global outdoor coverage. The second is global system for mobile communication which is used for both outdoor positioning and indoor positioning system.

3.1.1 Global Positioning System (GPS)

Global Positioning System is a satellite based navigation system made up of a network of 24 satellites placed into orbit by the U. S. Department of Defence (DOD). GPS was originally intended for military applications, but in 1980s, the government made the system available for civilian use also [Sørensen, 2003].

GPS works 24 hours a day any where in the world and works in any weather conditions. The spacing of the satellites is arranged in the way that a minimum of five satellites are in view from every point on the globe. There is no subscription fee or setup charges to use GPS [Sørensen, 2003].The main principle behind the GPS is the distance between the receiver and the satellites. The distance can be calculated by estimating the amount of time for GPS signals to reach the receiver. When the GPS receiver finds distance to at least three GPS satellites then it can calculate its position in two dimensions (latitude and longitude) and when four or more satellites are

________________________________________________________________________21

Page 25: Location and Time Based Information Exchange System

________________________________________________________________________in view, the receiver can determine the user's 3D position (latitude, longitude and altitude) [Sørensen, 2003].

GPS satellites circle the earth twice a day in a very precise orbit and transmit signal information to earth. GPS receiver on earth receives this information and use triangulation to calculate the user’s exact location. GPS receiver compares the time, when a signal was transmitted by a satellite with the time it was received. The time difference tells the GPS receiver how far away the satellite is from the receiver [Sørensen, 2003].

GPS gives good results for outdoor environment only. Now the question is, Does GPS can also work in the indoor environment? The simple answer of this question is No because the “GPS signal will not pass through most solid objects such as buildings and mountains [Sørensen, 2003]. The GPS signal is reflected by objects such as tall buildings or large rock surfaces before it reaches the receiver. This increases the travel time of the signal, thereby causing error. Because of this reason GPS doesn’t give good results near tall buildings.

3.1.1.1 How Does GPS Positioning System Work?

The whole idea behind GPS is to use satellites in space as reference points for locations here on earth. By accurately measuring the distance from three satellites, can triangulate the position of a mobile device any where on earth.

Transmission time between the satellite and the mobile station can be measured. This time finding is very tricky and difficult. Precise clocks are needed to measure transmission travel time [Yousaf, 2002]. The satellite positions are known, let ta, tb and td is the transmission time from three separate satellites. The distance measurement from three satellites is calculated by multiplying the transmission time to the velocity3.The three distances which has been calculated shows the mobile is on the spheres that are ta x c, tb x c and td x c miles away from the first, second and third satellite. It means that the position of mobile device on the surface of the earth is the intersection between these three cones. Each satellite is on the top point of the cone with a side length of ta x c, tb x c or td x c. It is illustrated in Figure (3.1.1.1) and Figure (3.1.1.2) [Sørensen, 2003].

3 Velocity is the velocity of light which is equal to 1, 86, 000 miles per second.________________________________________________________________________

22

Page 26: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (3.1.1.1): Mobile device on the surface of earth. Its position is determined by the intersection of the

cones with side lengths ta x c, tb x c and td x c (where c is velocity of light) (source idea [Sørensen,

2003])

Figure (3.1.1.2): Satellite is on the top point of a cone with a side length of ta x c. (source idea [Sørensen,

2003])

________________________________________________________________________23

Page 27: Location and Time Based Information Exchange System

________________________________________________________________________3.1.1.2 Advantages of GPS

The system works all over the world.

It is free for all civilians. One can request and receive positions.

It is a reliable system.

It gives good accuracy for outdoor positioning in open terrains.

3.1.1.3 Disadvantages of GPS

It requires an extra hardware.

It requires a clear view to at least four satellites.

It doesn’t work in the indoor environment [Sørensen, 2003].

It also doesn’t work under water or under ground [Sørensen, 2003].

It takes a couple of minutes to get the first device positioning.

3.1.1.4 Sources of Error in GPS

Ionosphere and troposphere delays

Signal multi-path

Receiver clock errors

Orbital errors

visible number of satellites

Satellite geometry/shading[Sørensen, 2003]

3.1.2 Global System for Mobile Communication (GSM)

Global system for mobile communication is globally accepted standard for digital cellular communication. GSM is the name of a standardization group established in 1982 to create a common European mobile telephone standard that would formulate specifications for a pan-European mobile cellular radio system operating at 800-900 MHz or 1800 MHz [IEC, 2003]. It was first deployed in 1992 and is now widely used around the world. The abbreviation GSM derives from Group Special Mobile.

________________________________________________________________________24

Page 28: Location and Time Based Information Exchange System

________________________________________________________________________

3.1.2.1 GSM Network

GSM network is divided into the following four elements

The mobile station

The Base Station System (BSS)

The Network Switching Subsystem (NSS)

The Operation and Support Subsystem (OSS)

NSS

OSS

BSS

MI S

AUC

HLR

MSC

VLR EI R

BSC

BTS

SI M

PSDN

I SDN

PSTN

PLMN

A interface

Abis interface

Figure (3.1.2.1) General architecture of the GSM network (Source idea [IEC, 2003])

The first element mobile station is the equipment carried by the subscriber. It consists of a mobile terminal and a smart card called the Subscriber Identity Module (SIM). The second element is Base Station System (BSS). It consists of Base Transceiver Station (BTS) and the Base Station Controller (BSC). BTS handles the radio interface to the mobile station. The BTS is the radio equipment needed to serve each cell in the network. A group of BTSs are controlled by a BSC. BSC provides all the control functions and physical links between the Mobile Switching Centre (MSC) and BTS [IEC, 2003].

________________________________________________________________________25

Page 29: Location and Time Based Information Exchange System

________________________________________________________________________The third element is Network Switching Subsystem (NSS), which manages the communication between the mobile users with other users. NSS contains MSC, which performs the connection and switching services to other networks. NSS also contains Home Location Register (HLR), Visitor Location Register (VLR), Equipment Identity Register (EIR) and the Authentication Centre (AuC). The fourth element, Operation Support Subsystem (OSS) connects the different components of NSS to the BSC. OSS controls and monitors the GSM system [IEC, 2003].

3.1.2.2 How Does GSM Positioning System Work?

There are a variety of ways in which the position of the mobile phone can be derived from the measurement of signals, and these can be applied to any cellular system, including GSM. The most important measurements are propagation time, time difference of arrival, angle of arrival etc. Each measurement defines a locus on which the mobile phone must lie. The point at which the loci from multiple measurements intersect defines the position of the mobile phone.

Propagation Time

This method involves measuring the time that a signal takes to travel between a base station and a mobile telephone or vice versa. Measurement constrains the position of the mobile telephone to a circular locus around the base station. If other propagation time measurements are made with respect to a second and third base station, two more circles loci are produced. Position determination is the point of intersection of three loci. The system which makes propagation time measurements is also referred as a circular-circular-circular system.

________________________________________________________________________26

Page 30: Location and Time Based Information Exchange System

________________________________________________________________________Angle of Arrival

This method involves measuring the angle of arrival of a signal from a base station at a mobile telephone or vice versa. A single angle measurement produces a straight line locus from the base station to the mobile telephone. Another AOA measurement from second base station yields a second straight line. The intersection of the two straight lines gives the position of the mobile.

Time Difference of Arrival

A mobile telephone can listen to a number of base stations and measure the time difference between each pair of arrivals. From three base stations two independent TDOA measurements can be made. Each TDOA measurement defines a hyperbolic locus on which the mobile telephone must lie. The intersection of the two hyperbolic loci will define the position of the mobile telephone.

3.1.2.3 Advantages of GSM

Every device with a GSM card can be positioned outdoor, so it does not

require any extra hardware or software.

GSM signals are much stronger than the GPS signals, therefore it can

also work in indoor environment.

It takes very short time to locate a phone.

3.1.2.4 Disadvantages of GSM

The accuracy depends on the kind of base station that the phone is

currently communicating.

The accuracy depends on distance between the phone and the base

station.

There can be some problems with the indoor positioning since the

accuracy is not well (up to 87 meter) [Sørensen, 2003].

________________________________________________________________________27

Page 31: Location and Time Based Information Exchange System

________________________________________________________________________This system can be used for indoor environment but because of the accuracy problem this system is not generally preferred for indoor positioning. For the development of indoor location based services, it is necessary to look any other accurate system that can give more accurate location of mobile devices.

3.2 Indoor Positioning Technology

From the discussion of previous sections, it is concluded that GPS system is very useful positioning system in outdoor environment. The line of sight to GPS satellites is not available inside buildings and hence the GPS system cannot be used in indoors [Yousaf, 2002]. GSM has accuracy problem for indoors positioning. Therefore for indoor positioning some other positioning methods is needed.

A variety of signalling techniques, system architectures and location finding algorithms exist and are being developed to achieve more accurate location estimate and tracking indoor mobile devices. Accurately locating and tracking the user in an indoor environment is an important issue for commercial, military and public safety applications. Tracking people with special needs, to navigate the blind, to track inmates in prisons, to navigate policeman, fire fighters and soldiers to complete their missions inside the buildings are some of the application areas of the indoor geolocation systems and they have initiated research for modelling radio channel indoors and developing new technologies [Pahlavan, 2002].

To fully understand the theory and technology of the indoor positioning system, it is necessary to understand fundamentals of the wireless local area network and also the Ekahau Positioning Engine (EPE). “Ekahau Positioning Engine is one of accurate positioning server for wireless LAN. EPE is a powerful software solution that enables a variety of new location based applications for wireless PDAs, Laptops and any IEEE 802.11 embedded devices” [Ekahau, 2002].

3.2.1 Wireless Local Area Network (WLAN)

The increasing demand for mobility in the daily life emerges the development of wireless LAN. The significant difference a WLAN has from a wired LAN is

________________________________________________________________________28

Page 32: Location and Time Based Information Exchange System

________________________________________________________________________mobility. The benefit of the mobility is that the LAN goes where ever you are, instantly and without any prior arrangement with the network administrator.

Wireless LAN system can provide LAN users with access to the real time information anywhere in their organization. A laptop equipped with wireless LAN connection can avail all the services which were available in the office, are still available in the conference room, lobby and in the indoor parking area [Petrick, 1999].

IEEE made the first WLAN standard for 2.4 GHz Industrial, Scientific and Medical band (ISM) in 1997 and denoted this standard by IEEE 802.11-1997. The goals of the IEEE 802.11 standard are to describe a wireless local area network that delivers services previously found only in wired networks, e.g., high throughput, highly reliable data delivery and continuous connections [Petrick, 1999].

IEEE 802.11 standard was designed to look like any IEEE 802.2 wired LAN. IEEE 802.11 operates under the IEEE 802.2 logical link control sub layer, providing all the services required supporting that sub layer (Figure (3.2.1.1)

I EEE 802.2Logical Link Control ( LLC)

I EEE 802.11Media Access Control (MAC)

Frequency HoppingS preadS pectrum PHY

DirectS equenceS preadS pectrum PHY

I nfrared

MAC

PHY

OSI Layer 2(Data Link)

OSI Layer 1(Physical)

Figure (3.2.1.1) IEEE 802.11 standards mapped to the OSI reference model

IEEE 802.11 architecture comprises several components: the mobile station, access point, wireless medium, the basic service set, the distributed system and the extended service set [Petrick, 1999]. Depending on the size of the covered area the following WLAN architectures can be used.

Independent Basic Service Set (IBSS)

________________________________________________________________________29

Page 33: Location and Time Based Information Exchange System

________________________________________________________________________

Basic Service Set (BSS)

Extended Service Set (ESS)

BSS is a set of stations that communicate with one another. The BSS uses one Access Point and all communication must go through this.

When all the stations in the basic service set are mobile and there is no connection to the wired network or AP, the basic service set is called Independent basic service set (IBSS). IBSS is also called ad-hoc network (Figure (3.2.1.2)). An ad-hoc network is typically created in a spontaneous manner and also for limited time.

Figure (3.2.1.2) General architecture of adhoc and infrastructure basic service set

An Extended Service Set (ESS) is a set of infrastructure basic service sets where the access points communicate among themselves to forward traffic from one basic service set to another. The AP performs this communication via an abstract medium called the distributed system. An important hardware in wireless LAN configuration is Access Point and is discussed in section below.

________________________________________________________________________30

Page 34: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (3.2.1.3) General architecture of extended service set

3.2.1.1 Access Point (AP)

Access Point is used to connect the wireless LAN to the wired network by using standard Ethernet cable and be able to communicate with the mobile station. Access Point is receiver/transmitter device also called transceiver. A general WLAN architecture has number of access points, which receives and transmits data between the WLAN and wired network infrastructure.

One Access Point is capable to support small group of mobile devices. In the wireless network access points should be properly installed. It is good to install them near roof so that the walking people and other equipment placed on the area do not obstruct the signals and it gives the maximum radio coverage. Before installing the access points, detailed site survey of the area of interest is necessary. The line of site of access point must be clear.

In order to access the wireless LAN, one must install LAN adopter (wireless LAN card). A variety of wireless LAN cards are being used, the most common are Avaya, ORiNOCO, HP, IBM, Nokia etc. Wireless LAN adopters provide an interface between the client network operating system and the air waves via an antenna. Supporting wireless LAN cards and drivers for different operating systems can be found in [Ekahau, 2002].

________________________________________________________________________31

Page 35: Location and Time Based Information Exchange System

________________________________________________________________________At the beginning six Access Points were installed as shown in Figure (3.2.1.4) for wireless LAN and for positioning purposes but at present 13 Access Points have been installed.

Figure (3.2.1.4) Position of access points at ITU (source [Sørensen, 2002])

3.2.1.2 Advantages of WLAN

The main advantage of the WLAN is mobility.

Wireless LAN can be configured in a variety of topologies to meet the

need of specific application.

It eliminates the need of wires.

The installation speed of WLAN is fast as compared to wired network.

________________________________________________________________________32

Page 36: Location and Time Based Information Exchange System

________________________________________________________________________3.2.1.3 Disadvantages of WLAN

Main drawback of Wireless LAN’s is security concern. IEEE 802.11b

addresses this issue in wired equivalent privacy (WEP).

WLAN protocol 802.11b works in an unlicensed 2.4 GHz ISM band.

Some other appliances such as microwave oven, cordless phones etc

also share this bandwidth. This may also cause interference in the

propagation of the radio waves between the access point and mobile

user.

3.2.2 Ekahau Positioning Engine

Ekahau is a building wise tracking system based on IEEE 802.11 wireless LAN. Ekahau measures the received signal strength sent by wireless devices and compute their 2D position and level within a building. There are so many other wireless positioning techniques have been published and are being implemented in the indoor applications, but the choice is Ekahau Positioning Engine because of two reasons. First and major reason is that it is the only positioning engine that is running at ITU and second Ekahau Positioning Engine TM 2.0 is one of the best systems that give very good positioning accuracy for indoor wireless LAN devices [Tornado, 2003].

Ekahau Positioning Engine TM 2.0 is fully software-based system, which enables location-based applications for wireless LANs. Ekahau Positioning Engine TM 2.0 is powerful java-based positioning server that calculates the location of mobile device in coordinates like (x, y, level). The complete positioning system includes the Ekahau Client, Ekahau Positioning Engine and Ekahau Manager. Each mobile device that the system wants to track must have installed the Ekahau client software.

Ekahau Positioning Engine offers a Java application-programming Interface that is used to create location-based applications. Developers of LBS application have the following two options to develop their applications on top of Ekahau positioning engine.

Via Ekahau Java SDK

________________________________________________________________________33

Page 37: Location and Time Based Information Exchange System

________________________________________________________________________

Via LaCoMoCo WEB API

In order to retrieve the positioning data from connected clients in the network, Ekahau provides their own Java API and SDK which is compatible with Java2 SDK (version 1.4 and up). The Ekahau Java packages must be imported in the application and the client must be able to access the positioning server via the TCP/IP socket.

Ekahau Positioning Engine TM 2.0 has many good features that make it attractive to use for indoor environment like its compatibility with IEEE 802.11b WLAN, Java2 SDK and accuracy etc.

3.2.2.1 Advantages with Ekahau Indoor positioning

It gives good accuracy for the indoor applications.

The average accuracy is up to 1 meter (3 ½ feet) [Sørensen, 2003].

It is easy to implement.

It is software based only.

It can locate over 100 devices per second.

It works over any wireless LAN.

It is compatible with major WLAN network adapters.

It does not require any special hardware installation.

3.2.2.2 Disadvantages with Ekahau Indoor Positioning

It is difficult to setup and calibrate.

Each mobile device that the system tracks requires special software

[Geier, 2002].

Instability of the system in case of failure of one or more Access Points.

3.2.2.3 How Does the Positioning System for Indoor Location

Work?

________________________________________________________________________34

Page 38: Location and Time Based Information Exchange System

________________________________________________________________________In this section it will be discussed how the indoor geolocation works. The main objective is to find out the location of a mobile device in an indoor environment. Figure (3.2.2.1) illustrates the functional block diagram of a wireless geolocation system [Pahlavan, 2002].

P o sitio n in gA lg o r ith m

L o ca tio nS en sin g

L o ca tio nS en sin g

D isp la yS y stem

R ece iv edR F sig n a l

L o ca tio n m etr ic s:T O A ,A O A ,R S S

L o ca tio nco o rd in a tes(x ,y,z )

Figure (3.2.2.1) Functional block diagram of wireless geolocation system (Source [Pahlavan, 2002])

This block diagram shows that main elements of the system are, a number of location sensing devices that measure metrics related to the relative position of a mobile terminal with respect to a known reference point, a positioning algorithm that process metrics reported by location sensing elements to estimate the location coordinates of mobile terminal and a display system that illustrates the location of the mobile terminal to users [Pahlavan, 2002]. The common location metrics are angle of arrival, time of arrival and received signal strength.

Indoor systems using the existing wireless LANs may use RSS, AOA or TOA. Pattern recognition positioning algorithm technique (Figure (3.2.2.2)) is used to find out the location of a mobile device, based on the following two phases.

Training phase - also called Learning phase, off-line phase or manual

calibration phase. It is the data collection phase.

Real-Time phase – is the phase in which the position of mobile device

is determined.

________________________________________________________________________35

Page 39: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (3.2.2.2) Pattern recognition based indoor localization (Source [Sørensen, 2002])

Training phase (off-line phase) consists of recording a set of information in a database as a function of the user’s location covering the entire zone of interest, forming a set of fingerprints [Nerguizian, 2001]. The pre measurement-based location pattern recognition is also called location fingerprinting.

In off –line phase the most important thing is to describe the area of interest or the service area and this area must be restricted to inside a building. During calibration the whole area of interest is divided into non-overlapping zones or grids4 and signal strength at each known location is determined and stored in the database (shown in Figure (3.2.2.3)). The algorithm analyzes the received signal pattern and compiles a unique signature for each zone. In order to get good signatures, one has to collect many readings of signal strength by rotating 360 degrees to capture access point signals from all directions. This process is tedious and time consuming [Geier, 2002].

The received signal strength is a function of the amplitude of the signal, transmitted from the access point to the mobile terminal. The IEEE 802.11b standard contains a representation of the received signal strength, which is

4 Grids are the known locations are sample points where signal strength is recorded during calibration.________________________________________________________________________

36

Page 40: Location and Time Based Information Exchange System

________________________________________________________________________available in the driver for the Wireless Local Area Network Card (hardware). The received signal strength is the key information, needed for positioning using WLAN [Sørensen, 2003].

Figure (3.2.2.3) Data base of all fingerprints (Source idea [Nerguizian, 2001])

In Real-Time phase the position of a mobile device is determined. To locate the position of the mobile device user, the mobile device measures the signal strength of each of the access points within its range. It then searches through the database to determine the signal strength that best matches with the signal strength that it has measured. The system estimates the location associated with the best matching signal strength to be location of the mobile device (Figure (3.2.2.4)).

Fig (3.2.2.4) Pattern matching with the data base (Source idea [Nerguizian, 2001])

________________________________________________________________________37

Page 41: Location and Time Based Information Exchange System

________________________________________________________________________The specific search technique adopted by the pattern recognition algorithm is called nearest-neighbour method. In this method the Euclidean distance measure is calculated between the measured received signal strength metrics and all entities in the signature database. The location estimate is determined to be the one associated with the minimum Euclidean distance [Pahlavan, 2002].

When the area of coverage becomes large, then the size of the location signature database increases dramatically, which makes the use of simple nearest-neighbour pattern recognition computationally cumbersome. More complex algorithms like fuzzy logic, neural network, subspace techniques, hidden Markov model-based techniques, clustering algorithm etc are being investigated to reduce overall computational complexity and improve performance [Pahlavan, 2002].

3.2.2.4 Draw Backs of Pattern Recognition Algorithm

Since the working environment changes constantly, substantial effort

is needed in maintenance of the signature database.

For larger areas the size of the location signature database increases

dramatically.

Calibration is tedious and time consuming process.

Calibration needs revision periodically with changes in the building like

equipment, furniture and increase of population.

3.2.2.5 Assumptions for RSS Positioning

The received signal strengths in a Mobile terminal are different, if

measured in two indoor positions sufficiently apart. This corresponds to

a fingerprint.

The received signal strengths in a mobile terminal, measured in a

given indoor position at a certain time, must be the same strengths,

measured at a later time in that position [Sørensen, 2003].

3.2.2.6 LaCoMoCo WEB API

________________________________________________________________________38

Page 42: Location and Time Based Information Exchange System

________________________________________________________________________LaCoMoCo WEB API is an additional layer on top of Ekahau SDK. LaCoMoCo WEB API is a platform independent API and can be accessed via HTTP requests from any type of platform and client application [Cervera, 2003]. LaCoMoCo WEB API is an extra service for those who only desire to concentrate on the client side development. It provides the position of wireless devices by making a mapping between Ekahau system’s position and the rooms and floors positions at ITU. The extra service provided by this API is, an addition of room number to the retrieved position from the Ekahau positioning engine. The retrieved positioning parameters from LaCoMoCo are of form (x, y, floor, room). We need only the room number information from the positioning system to use in application.The architecture of the LaCoMoCo WEB API is illustrated in the Figure (3.2.2.5) below:

Figure (3.2.2.5) Ekahau SDK and LaCoMoCo WEB API (source [Cervera, 2003])

3.2.2.7 Possible Design Considerations for LTBIES

Before starting location based services application development by using Ekahau Positioning Engine, it is realized that one of the option from three possible system options can be applied in the application development.

By using LaCoMoCo WEB API

By developing our own WEB API

By using Ekahau SDK

By Using LaCoMoCo WEB API

As already has been discussed that LaCoMoCo WEB API is an extra layer on top of Ekahau SDK. It is platform independent and eliminates the dependencies of using and configuring the server side. It can be accessed via HTTP requests from any type of platform and client application. This

________________________________________________________________________39

Page 43: Location and Time Based Information Exchange System

________________________________________________________________________architecture has been implemented in final application implementation because the main emphasis is on the client side development.

Figure (3.2.2.6) LaCoMoCo WEB API

By Developing Self Define WEB API

Another way of developing the application is that, the design of self defined WEB API on top of Ekahau Positioning Engine that certainly provides the same facility like LaCoMoCo WEB API. In this case we will have to use Ekahau SDK to get the position of mobile device and mapping the position retrieved from Ekahau Positioning Engine with the floor maps of the ITU. This needs lot of work on the server side which has already been done by Mr. Anders Cervera and this platform is available for the students to develop their applications on this API, which offers acceptable results and give the information like (x, y, floor, room). Thus utilizing the facility of LaCoMoCo WEB API seems more logical and time saving.

Figure (3.2.2.7) Self define WEB API

________________________________________________________________________40

Page 44: Location and Time Based Information Exchange System

________________________________________________________________________

By Using Ekahau DK

Another approach of getting position of a mobile device is directly using Ekahau SDK. Drawback of adopting this type of approach is that then we will have to focus on the server side programming. This architecture cannot track J2ME enabled mobile devices, because J2ME does not support socket connection.

Figure (3.2.2.8) Ekahau SDK with direct GUI

After going through the pro and cons of all these three options, it is concluded that the most convenient design for this application is to use LaCoMoCo WEB API. Since the concentration is only on the client side development and from the application point of view the positioning system is just a concept for retrieving position of mobile device and is demonstrated in this application.

3.2.2.8 Indoor Positioning Test Bed at ITU

The present experimental test bed for indoor positioning system in IT University has the following salient features.

5 access points at the third floor [Sørensen, 2002].

1 access point at the second floor [Sørensen, 2002].

The positioning system is calibrated manually in approx 100 calibration

points.

The positioning area of interest is approx 600 sq meters at level 3

[Sørensen, 2002].

________________________________________________________________________41

Page 45: Location and Time Based Information Exchange System

________________________________________________________________________

The positioning system is from the Finnish firm Ekahau

(www.ekahau.com).

The position precision in the middle part of the ITU building is approx 2

meter.

Ekahau updates the location after every 2 second [Sørensen, 2003].

________________________________________________________________________42

Page 46: Location and Time Based Information Exchange System

________________________________________________________________________

4 System Design

In this chapter the system architecture of this application will be discussed, how it will be planned and designed to achieve the desired goals of this project. The main goal is to enable the users of this application to avail some indoor location based services which should also be time bound. So for enough positioning technologies has been explored that was necessary for location based services. Now we are going to design the system which brings the idea of time and location bound services into reality.

The overall system architecture can be described into the four main components. The components of system design are Server, Client, Database and Positioning server. Keeping in view the importance of these components, all components will be explained separately in brief along with an overview of suggested services which we are going to provide the application users, graphical user interface, system requirements and at the end of this chapter summary of all tools and techniques which will be used to develop this application. To keep the names of the system components unique, the application server, client and database will be called as LTBIES server, LTBIES client and LTBIES database respectively.

4.1 Database Design

Database is one of the most important modules of this application. The efficiency of the system depends mainly on the logical database design. At start of this project a lot of problems had been experienced with the database design. Our supervisor Kåre Jelling Kristoffersen gave some valuable suggestions and guided how to overcome these problems. Moreover he gave a book on database design [Korth, 1991], to conceive the idea how to manage good database for the projects like this. With his guidance and help from book, it could be able to manage a reasonable database which solves all the problems that were being faced at the beginning.

Figure (4.1.1) shows the relations and their attributes of the system database of this application. The important issue while designing the database was that how the data for all the services including location, time, user’s information etc are stored and accessed in LTBIES database relation as simple data types.

________________________________________________________________________43

Page 47: Location and Time Based Information Exchange System

________________________________________________________________________Persistent data storage is necessary to make the environment robust and to meet the long term storage requirements.

In this application, both client and server can access the LTBIES database. Client can directly communicate with the LTBIES database when there is no need of LTBIES server to be invoked and same situation is with position server where client gets the location without the involvement of LTBIES server. Application requirements were defined based on concept of services to ensure that the storage is persistent and is available for client server access.

Database is designed in a way that all the information needed for particular tasks are normalized5, in the particular relation like all resources needed for user authentication and registration is available in user’s relation and other application services like leaving messages and getting messages are available in message relation.

Entity6 Relationship Diagram is one of the most important elements of database design. ERD enables a software engineer to identify data objects and their relationships using graphical notations, ERD defines all data that are input, stored, transformed and produced within an application [Watson, 2002].

Entities are shown by rectangles relationships are depicted by diamonds. Attributes7 are shown as ellipse that connected to the entity or relationship to which they belong. A detailed ERD8 of LTBIES database is given below.

5 Normalization is a way of splitting up data until each table represents propositions about a single type of thing.6 An entity is a thing about which data should be stored, something we need to describe.7 An attribute describes an entity.8 ERD is the abbreviation of entity relationship diagram.________________________________________________________________________

44

Page 48: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (4.1.1): E/R Diagram of LTBIES database

LTBIES database is organized and divided into five domains of information in order to build a relational database9. The database design will be implemented in the MySQL and the data stored at the ITU’s MySQL server. LTBIES database can update location information dynamically from the positioning server and can also obtain data from manual inputs given by a group or student and system manager trained for the purpose. The LTBIES database performs general tasks like search based on keyword matching in terms of correctness, authenticity, and efficiency. The LTBIES database system should be maintained regularly by system manager, which involves addition of new materials, deletion of obsolete ones, and modifications to existing ones. Brief detail of all the relations is given below.

9 A relational database stores all its data inside tables and table is a set of rows and columns. The rows are analogous to a record and the columns are attributes of record.

________________________________________________________________________45

Page 49: Location and Time Based Information Exchange System

________________________________________________________________________

4.1.1 User Relation

This relation contains all the necessary information of users like user’s first name, last name, e-mail address and their corresponding passwords. This relation also contains the unique userID.

4.1.2 Group Relation

This relation contains the information of the group and groupID. This groupID will be used to send the messages to a group of persons who have the same area of interest like MMT, INT etc.

4.1.3 Message Relation

This relation is used to collect all the information for text messages. It contains all the messages, subject of the messages, areaID (This must be equivalent to areaID from location relation), start time, ending time (after that the message will be expired), mTo (i.e. message to, the name of person or group which must be equivalent to userID from the user relation or groupID from the group relation), mFrom (i.e. message from which must be equivalent to userID from the user relation), message status either the message has been delivered or waiting and the areaID (which is equivalent to areaID in the location relation).

4.1.4 Location Relation

This relation contains the information like areaID, usage (For what purpose this area is being used) and the general description if any.

________________________________________________________________________46

Page 50: Location and Time Based Information Exchange System

________________________________________________________________________4.1.5 Group Member Relation

This relation contains the information like groupID (This must be equivalent to groupID from group relation) and userID (This must be equivalent to userID from user relation).

4.2 Client Server Architecture

In this project a typical N-Tier10 client server architecture will be used to develop the proposed services. The idea of using the client-server architecture is to make design more flexible, portable and extendable. The client server model meets all these requirements. Another idea behind the client server architecture selection is to provide the server with fixed services which will be same to all clients. The main advantage of adopting this type of architecture is that the application server manages all the services for clients and also arranges the resources for those services. The special purpose of implementing client server design in this application is to get the physical position of mobile clients from Ekahau positioning Engine and by using this position to design some location based services like sending and getting messages at specific location for indoor environment. Figure (4.2.1) shows the overall system architecture of this application which illustrates the design more clearly.

The LTBIES server has been designed which works as the middle tier with direct access to the database and LTBIES client. The server is modelled as a perceptual process that waits for clients to connect and then process the client requests. Whenever a client contacts the LTBIES server on a particular IP address and port number, a socket connection is established serving that specific client. A socket is defined as one end point of a two way communication link between two programs running on the network, where the socket represents the connection between a client program and a server program. In order to identify one client from another, the socket is bound to a specific port number so that the TCP layer can identify the application, where the data is destined to be sent. For each socket connection, a thread is spawned serving only one client. LTBIES server is a multi threaded server and

10 Tier can be defined as "one of two or more rows, levels, or ranks arranged one above another" (see http://www.m-w.com/cgi-bin/dictionary?Tier). N implies for any number, like 2-tier, or 4-tier, basically any number of distinct tiers used in the architecture.

________________________________________________________________________47

Page 51: Location and Time Based Information Exchange System

________________________________________________________________________it can handle number of clients, where each client runs on a separate thread. The server can serve many clients concurrently.

Figure (4.2.1): System architecture

Client may be any mobile terminal, but keeping in view the limitation of mobile devices and also the memory problem the client is only laptop in this project and is distinguished with the word LTBIES i.e. LTBIES client. Once the server is running, the LTBIES client can start the log on procedure using the log on interface.

On log on interface the client also has access to the relevant information about the IP address of server in order to establish the connection to the LTBIES server. Client is also allowed to enter the IP address of server if it is running at some other machine. It means that it is the responsibility of the client to know the IP address of server where it is running and replace it if different than what is provided on the interface. In log on procedure the client sends the request with user name and password. The LTBIES server checks the name and password from the LTBIES database and if the client is a valid registered user then server sends back ok reply i.e. the client “user name” request has been accepted. If the log on procedure has been successful, the LTBIES client now can avail all the services of our application. Clients are also able to communicate directly with the Ekahau positioning engine for location determination and to the database if there is no need of application server.

________________________________________________________________________48

Page 52: Location and Time Based Information Exchange System

________________________________________________________________________

4.3 Positioning Server

A number of positioning systems have been developed and are available for positioning in indoor environment. In this application the position processing is carried out by the Ekahau Positioning Engine. Ekahau client must be running on the mobile terminal whose position is being determined.

To retrieve the position of a mobile client, a http request is send to the LaCoMoCo in the form

“http://server_address/TrackServlet?value=x,y,z&clientId=192.168.100.102&measure=pixels” and the response will be in the form

“3179.324480801351, 1325.092235752987, level4, 4.05”

What happens behind the position determination process is the signal strengths are received by the wireless PCMCIA11 card placed in the mobile unit where the client is running. The signals are sent by the Ekahau client to the Ekahau positioning engine that returns the physical position corresponding to the signal strengths which is stored in the database at positioning server during the area calibration process.

The positioning server returns the position in terms of physical coordinates like (x, y, z). On top of Ekahau SDK an additional layer called LaCoMoCo has been designed by Mr. Anders Cervera, which returns the position in terms of logical area information like (x, y, floor, room). In this application we get the location directly from LaCoMoCo web API (see more detail in § 3.2.2.6).

4.4 Simulated Position Server

Ekahau Positioning Engine is not an accurate positioning engine and some times it gives wrong location estimate, because of this wrong location all the services based on location could be affected. There are a number of reasons behind this in accuracy in positioning results e.g. calibration of area has been

11 PCMCIA is the abbreviation of personal computer memory card international agency________________________________________________________________________

49

Page 53: Location and Time Based Information Exchange System

________________________________________________________________________done a long time ago and it needs periodical recalibration, population, equipment and furniture has been increased which also obstruct the signals and the received signal strength suffers.

To overcome this problem and also for testing purposes, there is a need of some alternate arrangement. A Simulated Position Server has been developed keeping in view this problem, which defines the same area that Ekahau Positioning Engine has defined at time of its installation and calibration. Figure (4.4.1) shows the system architecture of Simulated Position Server.

Figure (4.4.1): System architecture of Simulated Position Server

In order to avoid any ambiguity, it has been kept in mind that the request and response format should remain the same as from the Ekahau Positioning Engine. The http request will be sent to the Simulated Position Server and one will get back the response in coordinates like (x, y, floor, room). This Simulated Position Server can be used for testing the location element of location based services. More detail of implementation and testing (see on § 6.2.1).

4.5 Suggested Services

________________________________________________________________________50

Page 54: Location and Time Based Information Exchange System

________________________________________________________________________Some suggested services will be discussed in this section for which the system are being planned and designed which have already been discussed in the previous sections of this chapter.

A number of location based services can be designed and implemented with different scenarios and of course some of the services are being developed and some has already been developed in ITU by different student groups. Most of these projects are location bound. When we decided to work in this area of LBS, first narrow down the proposed services of application location and time bound. The idea of these services was conceived with different scenarios (more detail of different scenarios can be seen in § 2.3) and found them more useful in the indoor environment. After discussing the whole idea of location based services especially time bound with the supervisor Kåre Jelling Kristoffersen and finally decided the following services with his consent.

Find out the location of a person (himself).

Find out the location of all online users of this application.

Track a particular person i.e. where is Mr. Henrik?

Leave and get messages.

Some alert (popup) messages.

An overview of all the suggested services is shown in Figure (4.5.1), and for better understanding of this application, we discuss all the suggested services in brief in section below.

________________________________________________________________________51

Page 55: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (4.5.1): Brief over view of the suggested services

4.5.1 My Location

This service should provide the present location of user himself/herself. After log on to application as registered or guest user, a user friendly interface of application gives the opportunity to the user to find his/her location by just clicking the button MY LOCATION and gets his location inside the building shown in terms of (x, y, level, room). User can also request to view his position on map by the option SHOW ON MAP.

4.5.2 Online Users

This service should serve as the location finder of all the connected users to the system. The system should display the list of all the users with their corresponding locations in different floors in the form of coordinates like (x, y, level, room). The application should also provide the service to see the users on any specific level (floor) by choosing floor number option in combo box. This application should also be able to view the position of all users on map.

________________________________________________________________________52

Page 56: Location and Time Based Information Exchange System

________________________________________________________________________4.5.3 Track Person

This service should be interested for a person who wants to track his/her friend by name (i.e. where is Bilal?). The application should be able to track the requested person and show the position of that person on map i.e. on which room the person is seated at present. For future work the application could be enhanced to implement routing and find the shortest path. This service counts as a valuable service for location based applications in an indoor environment especially in multi-storey and large size buildings where it is difficult to physically find the person’s location.

4.5.4 Message Services

The most important part of this application is the message service. This service should provide the information exchange between the users, where the user can get messages intended for him at his current location and also at specific time. The user can also send messages to any other user at a specific location in the building at a specific time. This application deals only text messages. After log on to application, one gets the application user interface (GUI). MESSAGE button on application GUI gives the user two more options leave messages and get messages. In leave message option user can send messages to any particular person or any particular group but by default to all at any predefined specific location and at specific time. Where as in get message option, user can get his messages which are addressed to him from any particular person but by default from all senders.

4.5.5 Alert Messages

Alert message is an emergency message or to alert the user for some immediate action. This message will pop up when LTBIES client enters a specific area for example when a person passes in front of examination hall he receives an alert message “be quite”. The importance of alert message in some scenarios is very vital.

________________________________________________________________________53

Page 57: Location and Time Based Information Exchange System

________________________________________________________________________

4.6 Graphical User Interface Design

A well defined interface is needed to the client for the services provided by this application. The user interface should be user friendly and windows oriented. Before final design and program coding we make a conceptual interface design for implementation.

User can interact with the application through two interfaces. Start interface shown in Figure (4.6.1) is used for authentication of the registered users and also provide the facility of registration for new users. If the user clicks on login button an authentication dialog box will open where the user will have to write the name and password. After successful authentication, main application interface shown in Figure (4.6.2) will be opened with welcome message like “Mr. Shouket, Welcome to location and time based information exchange system”. This interface should be user friendly and has menu buttons on one side of application GUI. All the services should be displayed at central area of the same window so that user can easily use different services and can see results on the same window without botheration and eye jumping at different places on different windows. Some screen shots of interface are given in appendix A4.

Figure (4.6.1): Start interface

________________________________________________________________________54

Page 58: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (4.6.2): Application main interface

4.7 System Requirements

The application will be developed in java programming environment. Users need java runtime environment to run this application. In order to perfectly run this application, the user system12 should have the following software and hardware requirements.

4.7.1 Hardware Requirements

The degree of robustness and performance of persistent application mainly depends on hardware of the system. The system should function correctly whenever application run on it. The following hardware is necessary to run the application.

Mobile terminal. For this project the mobile terminals are laptops.

12Systems contain integral parts and components. If there is a problem or malfunction within one of the components, it could cripple the full

system.

________________________________________________________________________55

Page 59: Location and Time Based Information Exchange System

________________________________________________________________________

Wireless LAN card13

Wireless network running in the indoor environment.

Database server (the hardware piece).

4.7.2 Software Requirements

Positioning engine for determining the position of mobile terminal.

Ekahau client software must be installed on mobile terminal.

Application client software.

Application server software.

Database server software for data storage.

The database server used for data storage is MySQL server.

Java 2 SDK (version 1.4 and up).

4.8 Tools and Techniques

In order to achieve the desired goal of proposed services, it is decided to use the following tools and techniques.

Mobile client in this application should be laptop.

Client to client communication for text only.

Socket client server network connection.

Client should be on mobile terminal.

Server should be on mobile or on fixed terminal.

Both client and server can run on the same mobile terminal or on

different machines.

Ekahau positioning engine is used for indoor location determination.

LaCoMoCo WEB API will be used for finding the location of mobile

terminal.

Java programming language is used to achieve all proposed services.

13 Wireless LAN cards are also called LAN adopter. A variety of wireless LAN cards are being used, the most common are Ayaya, ORiNOCO, HP,

Nokia etc.

________________________________________________________________________56

Page 60: Location and Time Based Information Exchange System

________________________________________________________________________

My SQL database server is used for data storage.

Windows oriented graphical user interface.

Updating the position of connected clients after every two seconds.

________________________________________________________________________57

Page 61: Location and Time Based Information Exchange System

________________________________________________________________________

5 Implementation

We were given a good deal of options (software and hardware) for developing application on a platform. This opportunity gave us a certain amount of insight into the important issues in developing and implementing mobile, context-aware applications. Our prototyping efforts were iterative, modifying software to improve functionality. When choosing hardware platform, we considered several mobile hand-held devices including mobile phone before deciding on the laptops. One of the driving considerations in deciding hardware was memory. The downside of this decision is the fact that for an organization it is not easy to give every user a laptop and on the other hand it is not practical on the users’ side to carry a weight like laptop all the time. However, in the near future the issues like size and memory will no longer remain because of the rapid development and technological advances in the field of mobile devices.

Mobile location services applications do require the complex systems integration of many different technology components. Therefore several technical issues needed to be well understood before final implementation of the application. The serious issues that have to be considered during the design of such an application are consistency guarantees provided to the clients, synchronization between the position server and the self-defined server, servers should be aware of the status of other servers in the environment and the way stored data is organized and accessed through database server.

5.1 Software Design

This part of the report will first explain application’s programming module and then it will describe how we have implemented the LTBIES Server, LTBIES client and LTBIES database. We will try to depict every important class and their methods for better understanding.

The design of the program was developed based on the above-described System architecture (chapter four) and its Specifications/Requirements. In order to create a communication network, two main areas of the software design were created: the Client and the Server. The description of the

________________________________________________________________________58

Page 62: Location and Time Based Information Exchange System

________________________________________________________________________program will be divided into two parts, the first referring to the Client side and the other referring to the Server side.

Figure (5.1.1): Application main interface

From the above diagram one can easily understand the two sides of the program. Moreover it is clear form the diagram that the client side of the program is interacting with the User, whereas the server side is oriented towards managerial work. Therefore these two sides will be discussed completely in different parts.

________________________________________________________________________59

Page 63: Location and Time Based Information Exchange System

________________________________________________________________________

5.2 LTBIES Programming Model

Java-programming language was used to develop this application. Java can make the server to wait for new clients to connect. When a client logs on to the server, a new thread is spawned and dedicates to handle messages from that client.  At the beginning this thread sends a welcoming message to the client acknowledging that it has been connected, and receives the user name that is stored in LTBIES database along with other parameters associated with this user for authentication purposes. The server should reject a client from logging on if another user already has the same user name. Once logged on, the server should be able to handle each client’s text messages. LTBIES server will be able to store messages in the database for further processing. It should be done whenever a new client arrives at the system.

A server responding to requests from multiple clients and servers needs to perform several tasks simultaneously. The programming model for such an application is usually based on either multithreading or event driven programming. We will take advantage of both in our programming model. We are going to use multithreading, in multithreading, concurrency is achieved by allowing different threads to perform independent tasks. Whereas, in event driven programming, against every button action a specific event is generated and this event leads to the execution of a specific code. The multithreaded model is easier to design, but debugging multithreaded programs is difficult because of the limitations of the existing debugger tools and complexity. The main function of server is to provide communication facility to its clients. The server should enable its clients to communicate with each other. It should also provide a mechanism for storing and retrieving objects. The server is multithreaded in order to process requests from many clients. The server has the following threads:

a) ‘Client worker’ thread. This thread - initializes other threads

b) ‘Server write’ thread, this thread is responsible to inform each client

that when it should read from the database.

In above described programming module there are some small modules which have been implemented and they are illustrated below with their short description.

5.2.1 LTBIES Client to LTBIES Server Communication

________________________________________________________________________60

Page 64: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (5.2.1.1): LTBIES client to LTBIES server socket connection

The application must be able to store and retrieve data such as messages or location. This data must be accessible by all users. Thus, the implementation should consist of at least two main parts: a LTBIES client part that can execute locally on an end-user’s mobile device and a LTBIES server part that provides common functionality between all clients. The main reason for this is that the location information and the data about usage of the messages have to be available centrally to all users. One of the most important responsibilities of LTBIES server is to maintain the list of all available users/clients. It does so to provide clients with the status of other clients to allow them to locate each other and get other services like get or leave messages. Another reason relates to the fact that LTBIES is a mobile service and as such it is subject to network connections and its quality. Therefore, it is desirable to maintain network connectivity otherwise it will not work.

5.2.2 LTBIES Client to Positioning Server Communication

Figure (5.2.2.1): LTBIES client to LaCoMoCo (WEB API) HTTP connection

In the application client will also communicate with the positioning server by sending an HTTP request to the positioning server. This positioning server resides on the ITU server. LTBIES client does this communication with the ________________________________________________________________________

61

Page 65: Location and Time Based Information Exchange System

________________________________________________________________________position server to get the position of other clients along with its own position. On the basis of this positioning it provides other services. Practically client sends an HTTP request to the positioning server with a predefined format”http://server_address/TrackServlet?value=x,y,z&clientId=192.168.100.102&measure=pixels” and in return the positioning server will response with a format “3624.475983266959,1149.5646103746471,level3,3.19” like this.

5.2.3 LTBIES Client and LTBIES Server to LTBIES Database

Communication

Figure (5.2.3.1): LTBIES client and LTBIES server connection with LTBIES Database

LTBIES client and LTBIES server both can communicate with LTBIES database. LTBIES serve use communication with LTBIES database to achieve client authentication from the database. Server also deletes the expired messages form the database. Server is responsible for deleting those messages, which has reached their maturity (message end time) seven days ago.

LTBIES client has communication with LTBIES database. LTBIES use it to get and put messages in to the database. The main advantage of this communication of client and database is to share load form the LTBIES server.

5.2.4 Client Side Classes

________________________________________________________________________62

Page 66: Location and Time Based Information Exchange System

________________________________________________________________________

First the classes on client side will defined along with their functionality. After that they will be discussed in detail with their methods to give an overview of their working in the program. This discussion also includes their interaction with each other in this package.

class ClientOn client side this class includes the main method.

class LoginThis class is used to provide option to the registered users for getting in the system.

class GuestThis class is responsible for taking care of Guest users on client side of the application. Its responsibility is to provide user interface to every guest client who logs on to the server.

class RegisterThis class is providing the option of becoming a member to the system by filling a form, and allows the client to become a registered user on the server soon after.

class MainThis class mainly includes GUI components. This class represent the Main interface to the client.

class MessageThreadThis class is always running and keeps checking messages, location and time for the client. It is also responsible for keep informing the client about messages by showing a popup window.

class MainListenerThis class is responsible for listening actions events on buttons.

class getMessage and class leaveMessageFormThese classes are responsible for providing the client facility of receiving or leaving a message from other clients.

class myLocation

________________________________________________________________________63

Page 67: Location and Time Based Information Exchange System

________________________________________________________________________

This class is used to provide client his location in the form of coordinates and area form Ekahau positioning engine via LaCoMoCo.

class showOnMap and class showOnMapAllAgainst button actions these classes are providing the position of the client on the map. Class showOnMap shows a single person on the map where as showOnMapAll shows all users on the map.

class TrackpersonIt is used to find out the position of a particularer person. It returns the position as a text message on the map and shows this message on the map.

5.2.5 Server Side Classes

Here first classes on server side will be defined, by their very functionality. After that they will be discussed in detail with their methods and their interaction with each other in complete package.

class ServerOn server side this class includes the main method. This class is always keep listening for the clients, as soon as it hears form a client it immediately allocates a thread to the client.

class clientWorkerAfter the initialization of class Server it takes the responsibility of taking care of that particular client.

class SeverWriteThreadServer initiates this thread to take messages for the client. This thread is responsible to inform the client about when to read from the message database. This information it will deliver to client after checking the flag. This class is responsible of taking care of those messages which are written by the client.

Helping Classes

________________________________________________________________________64

Page 68: Location and Time Based Information Exchange System

________________________________________________________________________These classes have been developed to add more functionality to the existing classes among them one class is created for a very important purpose of simulation.

class SimulationFOrmFor performance evaluation of application, class simulation was developed, which provides a simulation form.

class CustomScrollPanTo make interface more practical and functional this class was developed, which is responsible for providing scroll bars on every window of the application, where it is necessary to scroll down or scroll up.

________________________________________________________________________65

Page 69: Location and Time Based Information Exchange System

________________________________________________________________________

5.3 Server Side Implementation

The Server side classes provide the connection for communication and keeping updated the port and keep listening for new clients to connect with user names and status. Furthermore, the Server side classes also include connection with database, which keep messages and information about clients. The connections between the classes on the Server side are shown in UML diagrams of the classes on the Server side.

C lien t

L og in

R eg ister

G u est

M ain M yL ocation

getM essage

Tra ck P erso n

O n lin eU sers

S h o w O n M a p A ll S h o w O n M a p

c lien tR ea d th rea d

m essa g eth rea d

L ocation

Figure(5.3.1): UML Diagram of ClientWorker class

________________________________________________________________________66

Page 70: Location and Time Based Information Exchange System

________________________________________________________________________In LTBIES implementation we are initializing a Server socket object in order to make a socket connection for every incoming client. Generally a network connection between client and server is made through sockets. A socket connection is defined as one end-point of a tow way communication system, which links two programs running parallel on the network. This socket tends to connect these programs, which are called client and server. Server runs on a specific computer and has a socket for communication and listens on a specific port. It basically waits and “listens” until a client requests a connection. In order to differentiate one client form another client, socket is bound to a specific port number so that the TCP layer can easily identify, which client application has asked for the data.

The client should know the hostname/IP address of the computer on which the server is running and also the port number to which the server is connected. If the server accepts the connection request from the client, the server makes a communication link with the client from this socket. Then the port on the server that waits and “listens” is available again and ready to receive new connection requests from other client(s) and at the same time creates to the needs of the connected client. This socket connection can be seen in the following figure.

Figure(5.3.2): Client server socket connection

In this implementation a package called Java.net have been used that provides two classes socket and serverSocket each of which is responsible for implementing client side and sever side of the communication.

public static void main(String[] args){

________________________________________________________________________67

Page 71: Location and Time Based Information Exchange System

________________________________________________________________________

Server frame = new Server();

frame.listenSocket();

}

public void listenSocket(){

server = new ServerSocket(9786);

while(true){ ClientWorker w; try{ new ClientWorker(server.accept(), textArea).start(); }

}

Here above mentioned main method starts the application server and the second listenSocket () method opens a serverSocket and a new loop that always listen for a client connection when a client does so it runs the following client worker thread object.

protected void finalize(){

server.close();

System.exit(-1);

}

When ever the server goes down this method will execute and close the socket connection.

After invocation, LTBIES server has to perform some tasks along with the initialization of server socket in order to provide the clients better services. These tasks are listed below.

LTBIES server opens the socket connection for the client on the

specified port number.

LTBIES spawns a new session thread every time a new LTBIES client

approaches. After establishing each connection it again starts waiting

for a new client.

________________________________________________________________________68

Page 72: Location and Time Based Information Exchange System

________________________________________________________________________

LTBIES server tends to establish a database connection by running a

calss ‘ClientWorker’.

LTBIES server then performs user authentication.

This class ‘ClientWorker’ further initializes one class, class ‘server write

thread’.

Class ‘writethread’ after initialization will take the complete

responsibility of all further communication with the clients.

Class ‘ClinetWorker is used to make communication between LTBIES database and LTBIES server. This class has been implemented for server to database connection and the LTBIES server will use this connection for user authentication from the database. The below shown methods can easily depict this communication. Moreover main services off the application can be accessed from the LTBIES server by requesting the database.

public void firstStep(){

while(true){

try{

line = in.readLine();

}

StringTokenizer st=new StringTokenizer(line,"'");

if(st.hasMoreTokens()){

type=st.nextToken();

}

if(type.equals("G")){

//Authenticate the guest user

}

if(type.equals("L")){

// Authenticate the user as Login

}

if(type.equals("R")){

// Authenticate the user as Guest

}

out.println(“true/false”);//send the response back to client and break the while loop

}

________________________________________________________________________69

Page 73: Location and Time Based Information Exchange System

________________________________________________________________________firstStep() method is responsible for checking the initial communication between the client and the server to let the client login.

public boolean UpdateQuery(String Q){

Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();

stmt.executeUpdate(Q);

stmt.close();

}

public boolean query(String Q){

Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(Q);

}

When there is a registration request from a client arrives updateQuery() method is executed and store the data in the database. When there is a login or guest request arrives from the client query() method is executed and returns true or false accordingly. These methods are given below.

5.3.1 Database Connectivity

In this application database design and its implementation was considerably important. Decision of using a central class in the application was taken, which is providing the database connectivity to both LTBIES server and LTBIES client. This class has been implemented as a singleton for connectivity. The reason of this singleton connectivity is that there is only one time database connection is needed either it is from the server or from the client. The following discussion shows that how this was achieved.

Establishment of LTBIES database connection with client and server is essential because LTBIES database holds different data relations14 [Ullman,

2002] each of which is responsible for its unique data. For example, in here the user relation is used for storing information about user like their names, email address user ID and password, where as location table is used for

14 Relation is a database term which defines the data in the form of rows and columns. A relation is also called a table.

________________________________________________________________________70

Page 74: Location and Time Based Information Exchange System

________________________________________________________________________storing information about locations along with some short description about their physical environment and usage. Each of this information can be accessed and processed through LTBIES server by sending quires to the database.

JDBC drive makes it easy for Java programs to communicate with the relational database. Here one can see that how this private database connector takes a url string along with other parameters as arguments and establishes a connection. Another important argument is a driver, which has been downloaded in the package to make this connection. “com.mysql.jdbc.Driver” is a suitable drive to establish connection between java programs and MySQL relational database. To load this JDBC driver a statement class.forName (“com.mysql.jdbc.Driver”) is used. DriverManager.getConnection(url,username,password) gets an internet type of network connection to the database. Statement object provides functionality to build a query and eventually execute it. This also returns a Resultset. If the network connection goes down an exception can be thrown.

Class.forName("com.mysql.jdbc.Driver").newInstance();

String username = "na_e2002";

String password = "******";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;

Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(Q);

stmt.executeUpdate(Q);

Different SQL statements are used to perform actions on database. Sometimes it is required to get records from the database and sometimes it is used to add new records into the database. The formats of these quires are given below.

SELECT userID FROM users where userID ='Jelling'SELECT * FROM users where userID = 'Nadeem' and password= 'gujrat'INSERT INTO users VALUES('jelling','Kristoffersen','[email protected]','Kristoffersen','jelling')

Above-illustrated quires show some quires with their structure. They also show that how different types of informations are being accessed by LTBIES server. Some other quires with their respective methods have already been discussed on page 68.

________________________________________________________________________71

Page 75: Location and Time Based Information Exchange System

________________________________________________________________________

5.4 Client Side Implementation

Up till now a very short description of the classes on client side along with their definitions has been given in which they were defined by their functionalities. In this very section all the classes will be discussed in detail with their functions and interaction with each other as mentioned earlier. Client Side discussion will start with a classes diagram.

In client side implementation class client is the main class which is responsible for initiating all relevant objects. As soon as a user starts the application on reaching the login step, the LTBIES client tries to establish a socket connection to LTBIES servers. The LTBIES server IP address has been set according to a localhost value, which is 127.0.0.1 or local host, in order to run the LTBIES server and LTBIES client on the same machine [Thomas].But if you want to make server on a different machine you have to change the IP address accordingly before establishing the connection. After this LTBIES client will create a socket connection to LTBIES server on port number 9786. T o elaborate these steps a part of the code is given below.

static PrintWriter out = null;static BufferedReader in = null;frame = new JFrame( "Location and Time Based Information Exchange System Ekahau");JTextField ipS;

________________________________________________________________________72

Page 76: Location and Time Based Information Exchange System

________________________________________________________________________String ip = "192.168.100.229";ipS.setText(ip),

int port = 9786;static Socket socket;

try { if (socket == null) { socket = new Socket(ipS.getText(), port); socket.setSoTimeout( 5000 ); } } catch (UnknownHostException e) { message.setText("Unknown host: " + e); } catch (IOException e) { message.setText("No I/O " + e); }

if (command == "Login") {

Login l = new Login(); } else if (command == "Register") {

Reg r = new Reg();}else if (command == "Guest") {

Guest g = new Guest();}

Above mentioned code is of the client class and its responsibility is to bring first visual interface for the client and make the socket connection with the server. PrintWriter and BufferReader objects are used to read and write from this socket connection. It also shows that after the socket connection stage program is holding the client for a period of time so that the LTBIES server can respond after adequate processing of the client request which certainly includes user authentication. At the same time we are giving a certain amount of time to client for waiting after that it will be considered as time out. In this application the time out is set to wait 500ms. Moreover if this socket connection is not been able to establish within this amount of time the request will be terminated and client has to send again a valid request. Class client is also responsible for receiving and sending button events to other three classes.

After providing the first interface with three options to the client, now this class has initiated one class among three classes Class Guest, class Login and

________________________________________________________________________73

Page 77: Location and Time Based Information Exchange System

________________________________________________________________________Class register. Each of these classes is now able to communicate with the class client worker which is ready to allocate the threads for further communication. If the user is a registered user the class login will be activated for user authentication by checking the password form database. This class has following methods which are providing these services.

private JTextField Tname;private JPasswordField Tpassword;

String text ="L'";text+= Tname.getText()+"'";text+= Tpassword.getText();Client.out.println(text );

String line = Client.in.readLine(); if(line.equals("true")){Main ma=new Main(Tname.getText(),"L",Client.socket);

If the user is not a registered user and he wants to become a member at the application the class register will be activated for storing user information in user table. This information will be collected from the user on a form and sent to the LTBIES server which then stores this information in LTBIES database. The same procedure is used to retrieve the information from the database because server has to maintain the user list just to check that, tow users should not have the same login or user name. This class has following form format and the methods which are providing these services.

private JTextField TUname,TFname,TLname,Tlogin,Tpass,Temail;

String insert="R'"+TFname.getText()+"','"+TLname.getText()+"','"+Temail.getText();insert+="','"+TUname.getText()+"','"+Tpass.getText()+"'";Client.out.println(insert );

try{ String line = Client.in.readLine();

if(line.equals("true")){ fram.setVisible(false); fram=null; Main ma=new Main(TUname.getText(),"G",Client.socket);}

elsemessage.setText("It is not a valid record please try again");

}catch (IOException ee){message.setText ("READ failed");

}

________________________________________________________________________74

Page 78: Location and Time Based Information Exchange System

________________________________________________________________________If a user does not want to become a member at this application he will be give an option of having a guest tour. For this purpose a class called Guest has been created which has the following methods.

String text ="G'";text+= Tname.getText();Client.out.println(text );

String line = Client.in.readLine();

if(message.getText().equals("true")){frame.setVisible(false);frame=null;Main ma=new Main(Tname.getText(),"G",Client.socket);

}elsemessage.setText("This name is already registered Please try with another name");

Now if the LTBIES client has initialized, it spawns a thread by calling a start method from class Main. Now this thread will remain intact until and unless client request to close the connection.

static JFrame frame;static HashMap userList = new HashMap();static HashMap messageList = new HashMap();

frame = new JFrame( "Location and Time Based Information Exchange System ");

if (command = = "Messages") {

if (command = = "exit") { frame.setVisible(false); frame = null; System.exit(0);}

If LTBIES client requests for closure or goes down form the LTBIES server, then this connection will be brought down and an IO Exception is caught. Soon after this disconnection server will update its list of client’s status and now the system will closedown by showing a message on the Client side. messageThread is responsible for delivering a message when ever it reaches to maturity. It will update the position after every two seconds just like Ekahau positioning engine is doing. Every time the LTBIES client is

________________________________________________________________________75

Page 79: Location and Time Based Information Exchange System

________________________________________________________________________notified by the positioning server it will check the status of messages for the LTBIES database, through the following methods.

Location loc=new Location(Cip);String Q="SELECT * FROM `messages` where mTo='All' or mTo='"+Main.user+"' and areaID ='"+room+"' and sTime < '"+sT+"' and eTime >'"+sT+"'"; if(areaID!=null){ ResultSet rs = stmt.executeQuery(Q); while (rs.next()) {

if (Main.messageList.get(messageID) == null){

Main.messageList.put(messageID, mFrom); jf.setVisible(true); } }}stmt.close();

To set the location of client a class location is called. This can be seen in the following part of the code.

private static String X,Y,Floor,Room;public int getX(){

return (new Double(Double.parseDouble(X)).intValue());}public int getY(){

return (new Double(Double.parseDouble(Y)).intValue());}public String getFloor(){

return Floor;}public String getRoom(){

return Room;}public String toString(){

return ("X:"+X+"\tY:"+Y+"\tRoom:"+Room+"\tFloor:"+Floor);}

public void getLocation( ) {

X=st.nextToken();Y=st.nextToken();Floor=st.nextToken();Room=st.nextToken();After the establishment of HTTP connection now it takes the location information from the positioning server.

________________________________________________________________________76

Page 80: Location and Time Based Information Exchange System

________________________________________________________________________In the above given code getFloor () method is getting the floor from LaCoMoCo WEB API. GetLocation (), This method is getting location in the form of coordinates x and y in pixels. GetRoom () This method is getting the room noumber from the LaCoMoCo for example room is 3.19.

For further simplification a comprehensive summery of above described steps is given below.

LTBIES client at very first step initiates class Client

LTBIES client establishes a socket connection with LTBIES server.

LTBIES client initiates further classes, class login, class Guest and class

register.

After authentication process a class called Main will be initiated which

will further initiate a class MessageThread? Main will also create a

HTTP connection with positioning server via LaCoMoCo.

Class MessageThread starts taking care of matured messages to check

which one of them is ready for delivery

LTBIES client Initiates class clientReadThread, which is responsible for

further communication with positioning server.

5.4.1 Exception Handling

Here mainly three exceptions are caught in the application. Afterwards the user is provided with the appropriate messages, related with those exceptions. First two exceptions are IO exceptions which are thrown, first exception is given to client simply when a socket connection request from the client is not accepted, second it catches an exception if a client disconnects from the application. Other exception is thrown by the database, it does so when it disconnects either from the client or from the server. This exception is important for the system. On event of every such exception a popup message will appear in front of the user and will inform him about the situation.There are some other exceptions that are covering a number of exceptions because so many exceptions can occur while running the application. There are a number of unpredictable failures that can occur in any program either by itself or by some external reasons. Let us take example of LTBIES system, consider that we are using socket connection, input/output streaming, ________________________________________________________________________

77

Page 81: Location and Time Based Information Exchange System

________________________________________________________________________database quires and positioning technology, now just assume that if the socket connection is lost or positioning server is not responding. All such failures lead us to a more flexible program where we can handle all such situations more accurately for the potential users of the system.

5.4.2 Implementation of Map Component

To show available users on map in any location based application is essential. For this application therefore map implementation was important. It is one of the basic services to show users dynamically on map. This problem was solved in two steps. First the advantage of Photoshop was taken to make it suitable for the application by giving it some colures, and then the second step was of its handling in java environment. In Photoshop, the map has been experimented with different sizes in different formats. The bitmap representation is easy to obtain (scanning) for any area and is relatively inexpensive to store and display. Scaling and rotation, however, are cumbersome with that representation. It was also important to improve the map in terms of it s description. Map was improved by editing in Photoshop and rewriting some of the information especially the room numbers that were on the original bitmap but were in poor quality, it was difficult to control the display of the decorations after scaling for a zoom in or out.

image=new ImageIcon(Floor+".png"){ public void paintIcon(Component c,Graphics gg,int l,int m){ super.paintIcon(c, gg, 0,0 ); g=gg; Set list=userList.keySet(); Iterator iter=list.iterator(); int draw=12; while(iter.hasNext()){ user=(String)iter.next(); ip=(String)userList.get(user); loc=new Location(ip); loc.getLocation(); pX=loc.getX(); pY=loc.getY(); String level=loc.getFloor(); Room=loc.getRoom(); if(Floor.equals(level)){ g.setColor(new Color(0,255,0)); g.drawString("Mr. "+user+" is in Area "+Room+" on Floor "+Floor,700,draw+12); g.setColor(new Color(255,0,0)); g.drawString(user,pX/4, pY/4+draw); draw+=12; } }

________________________________________________________________________78

Page 82: Location and Time Based Information Exchange System

________________________________________________________________________ } }; label.setIcon(image);

To show users dynamically on the map, map has to be update. In programming to achieve this a method has been made, this method paintIcon (Component c, Graphics gg,int l,int m) where ‘l’ and ‘m’ are the position coordinates form the positioning engine. This method will update the position after every two seconds regularly after its execution. Now user will be able to see his changing location on the map.

Figure (5.4.1.3.1): Sample map for fourth floor at ITU

Default color of LTBIES application is used to represent border of the

area.

Green color is used to represent the new edited room numbers.

Dark Brown writing with a drop shadow effect is used to represent the

information of levels.

5.5 Thread Handling

In this section threads will be discussed in detail along with their handling in the program, and how they have been implemented. LTBIES server has to accept multiple clients at a time; it can only do so if it is able to run threads

________________________________________________________________________79

Page 83: Location and Time Based Information Exchange System

________________________________________________________________________otherwise it will not be able to handle more then one client at a time. LTBIES client is also in need of threads to be concurrent [Colulouris, 2001]. Threads will be discussed for both LTBIES server and client respectively. Therefore, in this case the threads have been used to make the system multithreaded so that it can perform multitask [Colulouris, 2001]. Short descriptions of general issues involved in multithreaded programming are presented here for better understanding in our implementation.

5.5.1 Issue in Multithreaded Programs

The general issues in multithreaded programs are mutual exclusion, deadlock and starvation [Colulouris, 2001]. Data structures that are shared by different threads have to be protected by locks to ensure that operations on such data are atomic. When locks are used to ensure mutual exclusion, the possibility of ‘hold and wait’ or ‘circular wait’ may result in the occurrence of deadlock. Starvation occurs when the same thread keeps acquiring the lock leaving the other threads waiting for long periods of time to execute. The issue of starvation has to do with the design of the thread scheduler whereas it is the responsibility of the programmer to ensure mutual exclusion and deadlock freedom.

5.5.2 Threads for Server

On server side an Object is made available for each client and this object controls a thread listening to incoming messages and then contacts the session object to perform further tasks.

new ClientWorker(server.accept(), textArea).start();

After establishing a socket connection with a client LTBIES server spawns a session thread (ClientWorker), which further initializes another thread (writeThread). The following method in the clientWorker class controls this thread. class ClientWorker extends Thread {

public void run(){while(true){

String line=in.readLine();//read a authentication  request from the clientStringTokenizer st=new StringTokenizer(line,"'");

if(st.hasMoreTokens())

________________________________________________________________________80

Page 84: Location and Time Based Information Exchange System

________________________________________________________________________

String type=st.nextToken();

if(type.equals("G")){//Perform the authentication steps

WriteThread wt=new WriteThread();wt.start();

}

}

This thread is running continuously to check every incoming client request. We can see from the above described method that after if it receives a valid request from the client it checks its authentication and respond back to the client.

5.5.3 Threads for Client

To understand the role of threads on the client side let us take an example of LTBIES application where client is allowed to scroll down a page at the same time he is allowed to receive popup messages, can communicate with the servers or he can use any services among different services of this application without interrupting any of other tasks. In such situations concurrency is essential to better serve the client. Thus to make application more responsive threads have been used on client side otherwise the client would not be able to scroll down the help menu while the application is performing any other time consuming task like locating other users or similar tasks concurrently.

After establishing a socket connection with the server LTBIES client spawns a session thread (messageThread).This is responsible for popping up the mature messages and another thread (ClientReadThread) which is ready to read data from the database at any time.

5.5.4 Problem of Shared Resources

Access of shared resources in the program might have become a problem. If a program has threads that are competing for some common recourses problem of deadlock can occur [Colulouris, 2001], or any other unpredictable

________________________________________________________________________81

Page 85: Location and Time Based Information Exchange System

________________________________________________________________________results can occur. Now just consider an example of a LTBIES application where more than one client can access to a single or more clients through a single server In this case if programmer is not able to control this access of clients to the single server the deadlock can disturb this program.

In the program threads were needed to update a single shred recourse that is database. Threads are used to read and write in the database. In this case threads need to access a single shared recourse (database). To get rid of this problem of shared recourses.

5.6 Database Implementation

LTBIES database was organized and divided into five domains of information in order to build a relational [Ullman, 2002] database, which is depicted briefly in the following figures. The design was implemented in the MySQL. LTBIES database performs general tasks like search based on keyword matching in terms of correctness, authenticity, and efficiency. System manager, which involves addition of new materials, should maintain LTBIES database system regularly deletion of obsolete ones, and modifications to existing ones.

These SQL statements, which have been used to create these relations in MySQL, are presented below.

________________________________________________________________________82

Page 86: Location and Time Based Information Exchange System

________________________________________________________________________User Table

CREATE TABLE users ( userID CHAR(10) PRIMARY KEY, Fname CHAR(20), Lname CHAR(30), e_mail CHAR(30), password CHAR(30) NOT NULL

);

Group Members Table

CREATE TABLE groupMembers(groupID CHAR(10) PRIMARY KEY,userID CHAR(10) NOT NULL,FOREIGN KEY (groupID)REFERENCES group (groupID),FOREIGN KEY (userID) REFERENCES users (userID),

);

Group Table

CREATE TABLE group(groupID CHAR(10) PRIMARY KEY,description CHAR(255),FOREIGN KEY (userID) REFERENCES users (userID),

);

Location Table

CREATE TABLE location (areaID CHAR(6) PRIMARY KEY,usage CHAR(30),description CHAR(30)

);

Messages Table________________________________________________________________________

83

Page 87: Location and Time Based Information Exchange System

________________________________________________________________________

CREATE TABLE messages123(messageID TINYINT(6) PRIMARY KEY AUTO_INCREMENT,message TEXT NOT NULL,subject VARCHAR(30) NOT NULL,areaID VARCHAR(6) NOT NULL,sTime DATETIME NOT NULL,eTime DATETIME NOT NULL,mFrom CHAR(10) NOT NULL,mTo CHAR(10) NOT NULL,status CHAR(4),FOREIGN KEY (mTo) REFERENCES users (userID),FOREIGN KEY (areaID)REFERENCES location (areaID),FOREIGN KEY (mFrom) REFERENCES users (userID));

________________________________________________________________________84

Page 88: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (5.6.1) Relationship15 of LTBIES database tables

15 Relationship describes a linkage between two entities.________________________________________________________________________

85

Page 89: Location and Time Based Information Exchange System

________________________________________________________________________

5.7 Protocol Design

It is essential for this application to have a set of defined protocols by which it will practically implement the program. Therefore in this very section of the report we will go into the details of protocol structure and its design. Discussion will after the definition of Protocols.

5.7.1 Protocols

In networking and communications, the formal specifications that define the procedures to follow while transmitting and receiving data is called a protocol. Infect protocols define the format timing, sequence, and error checking used on the network [Kurose, 2002].

5.7.2 LTBIES Protocol Structure

To differentiate between the various types of information exchanged between the server and clients a protocol has been implemented, which is discussed below.

This application has two different protocols for client and server to send and receive messages and to exchange all sorts of information with each other. When the client or the server receives these protocol information streams, string separation is needed in order to send the information to the right places and activate the right methods. Switch orders activates different methods; depending on the first and the second characters on the received string.

5.7.3 Client to Server Protocol

The discussion will start from client side protocol. Following figure shows how client side protocol has been structured.

________________________________________________________________________86

Page 90: Location and Time Based Information Exchange System

________________________________________________________________________

Cleint Side Protocol String

This is the protocol string. First character of the string is defined as the protocol character, which is used to send, as a request for login from the client. The second part of the string is classified as information string.

The rest of the string contains sub strings with an unknown number of characters. In this case it is important to use one string separation method that uses specific separators in order to divide the string into suitable information sub strings. This method is the tokenizer, where a separator (’) is defined, and the next token (or sub string) is returned every time a separator is reached. We use the tokenizer when the string we want to separate only has a (’) as a separator.

________________________________________________________________________87

Page 91: Location and Time Based Information Exchange System

________________________________________________________________________5.7.4 Server to Client Protocol

This part of discussion has server side protocol. Following figure shows how the protocol of server side has been structured.

Server Side Protocol String

This is the server side protocol string. Here above presented protocol string shows one example of a string, it has been sent to client from the server. First character of the string is defined as the protocol character, which is used by the server to send, a list of users to the client. The second part of the string is classified as information string. This contains the rest of the information.

________________________________________________________________________88

Page 92: Location and Time Based Information Exchange System

________________________________________________________________________

6 Software Testing and Simulation

6.1 Software Testing

Software testing is a process of executing a program according to customer requirement with the intent of finding the bugs and identifying the weak and risk areas of the software system.

Software testing is one of the most important and changeling issue in software development to improve the quality of software system. Approximately 30 to 40 per cent of software development effort is used for system testing [Pressman, 2000].

Test can be carried out, by using one, among two ways. First, testing can be done for each line of code and second by testing the overall functionality of the program. These testing methods are called white box and black box testing respectively.

6.1.1 White Box Testing

White-Box Testing also known as glass box, structural, clear box and open box testing. Test focuses on the program control structure, where internal working of the methods is tested. Knowledge of the programming language is required for this testing.

In the development process of LTBIES white-Box testing was iteratively used. Function of each class and method was tested to optimize the processing and to remove the bugs and risks. A part of white box testing known as unit testing is discussed bellow.

6.1.1.1 Unit Testing

Unit testing focuses on the smallest compliable program unit. It is applied for each class. This testing was used to remove the bugs form the code. Right input and right out put form each method was also tested and appearance of GUI.

________________________________________________________________________89

Page 93: Location and Time Based Information Exchange System

________________________________________________________________________

Class Location is going to be discussed for unit testing as a sample. Class Location is responsible to make a http connection with the position server, and to get the position of a provided IP. Then it sets the class variables values, and provides these values on request.

public class Location{

private String X,Y,Floor,Room;

Location(String ip){

}

public void getLocation( ) {// get the position of a device and set the class variabls}

public int getX(){ // return the X coordinate }

public int getY(){// return the Y coordinate }

public String getFloor(){ // return the Floor}

public String getRoom(){ // return the Room }

public String toString(){ // return All values as string}

}

For testing main method of the class was defined and all other class methods were called. Results obtained from these methods were checked.

public static void main(String arg[]){String ip = "192.168.100.229";Location location=new Location(ip);location.getLocation();System.out.println(location.toString());System.out.println(location.getX());System.out.println(location.getY());System.out.println(location.getRoom());System.out.println(location.getFloor());

}

Output from above testing code is

X: 3179 Y: 1325 Room: 3.19 Floor: level3317913253.19level3

This output is the expected output from the methods of location class.

________________________________________________________________________90

Page 94: Location and Time Based Information Exchange System

________________________________________________________________________6.1.2 Black Box Testing

Black Box testing is also known as functional testing. This test is designed to validate the functional requirements without knowing the internal working of the program. Tester and designer are independent of each other. Tester does not need to examine the programming code. A user of the application is the best tester for black-box testing. Following two testing strategies in the black box testing are given for the LTBIES system.

6.1.2.1 Integration Testing

When unit testing is finished each and every unit is tested together for integration of the system. It makes it confirmed that different units of the system work together correctly.

Following tasks were defined for integration testing. Each task is using more than one unit of the classes.

Few tasks tested on the server side are presented bellow

Task Detail Expected Result ResultSocket Connection Always ready to make a socket

connection with the client Connection should be established

OK

Authentication Accepts a client request for authentication, it is a valid user name accept otherwise reject.

Accept /Reject OK

Database Connection Establish a database connection with the MySQL server

There should be no exception

OK

Listen From Client Always ready to listen from the clients

Should perform accordingly

OK

Write to Client Always ready to write to a client

Should send a string OK

Few tasks tested on the client side are presented bellow

Task Detail Expected Result Result

________________________________________________________________________91

Page 95: Location and Time Based Information Exchange System

________________________________________________________________________Socket Connection At the beginning make a socket

connection with the server Connection should be established

OK

Authentication Send a request to the server with login name.

Response of acceptance or rejection from server

Should send request to server

Should receive response from server

OK

Database Connection Establish a database connection with the MySQL to get messages record

There should be no exception

OK

Listen From Server Always ready to listen from the server

Should perform accordingly

OK

Popup Messages Always checks the messages for current location and time and show a popup window, if the message is mature

Should show popup window

OK

Actions on Buttons There are different buttons they should perform relevant factions when pressed

Should perform accordingly

OK

6.1.2.2 Validation Testing

Validation testing is one of the most effective testing strategies in the black-box testing. This test is basically designed to test the user’s expectations form the developed software. It means that system should behave according to user’s expectations. The LTBIES application was given to some students at ITU for validation testing and feed back from them was incorporated in final design. For example one point in the feed back was about the get messages. While testing a client got wrong message, this was the query problem that resulted in the irrelevant message delivery from the database. Query was corrected after this feed back. Interfaces were also improved. The functionality and reliability was much better after this feed back.

Following are some main behaviors and tasks that were set and tested for

LTBIES through the validation testing.

Graphical User Interface

________________________________________________________________________92

Page 96: Location and Time Based Information Exchange System

________________________________________________________________________In GUI testing it was tested that it should be easy to use, self explanatory and

it should provide easy navigation to the user.

Message Delivery

Delivery of messages were tested by the users and they were satisfied with

the results

Message Receiving

Arrival of messages were also tested by the users and they were satisfied

with the results

Location finding devices

Location testing was also done. Users were invited to see their locations and

other user’s location.

6.2 Simulation

Simulation is defined as to do or make something which looks real but is not real, it means that a system simulation is mimicking of the operation of a real system. Paul A. Fishwick defines the computer simulation as “computer simulation is the discipline of designing a model of an actual or theoretical physical system, executing the model on a digital computer” [Fishwick, 1999], so simulation is the execution of a model, represented by a computer program that gives information about the system being investigated. Figure (6.2.1) shows the general architecture of the simulation process. Simulation system takes the controllable16inputs, process these inputted values and return the output in response.

16 Controllable inputs are the inputs which are given by the person who is testing the system________________________________________________________________________

93

Page 97: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (6.2.1): Simulation system diagram

The reason of using simulation for LTBIES application testing is that Ekahau Positioning Engine does not give right positioning result all the times. Therefore it was very difficult to know that whether this application is able to deliver the message at right location and at right time or not. Our supervisor John Aasted Sørensen advised to develop a simulation test which creates the dummy environment for the location and time and the results would be checked by using simulation.

This section is further divided into two parts. One is simulation developed for LTBIES application and the second is simulation for other LBS application developers.

6.2.1 Simulation for LTBIES Application

A simulation has been developed to check the application’s behaviour for the location and time bound services at the ITU wireless LAN environment. The objective of this experiment is to check up to what extent the basic services are achieved while preserving functionality. The simulation for LTBIES application is designed to perform the following two specific tasks,

Check the messages bound for specific location

Check the messages bound for specific time

In the simulation time can be twisted trespassed for example the future messages can be predicted by simulating the data that has been collected from the past. We need two controllable inputs i.e. time and location. Figure (6.2.1.1) shows the simulation interface for LTBIES application. The simulation checks the messages of a particular person against predefined particular location and also for specific time.

________________________________________________________________________94

Page 98: Location and Time Based Information Exchange System

________________________________________________________________________

The detail of controllable input is given below

Area: The area information will come from the location table in MySQL database. The area combo box takes the list of the predefined areas from database and tester can select any area from this list where he wants to check the messages.

Time: Hours are from 0 to 23 and minutes from 0 to 55 with 5 minute interval i.e. 0, 5, 10… 55

Date: By default the current date will be displayed, but previous 7 days and next 7 days from current date can be selected.

Figure (6.2.1.1): Simulation interface

If the system has messages for a particular person against the inputted location and time, these messages can be received by starting the simulation process. So by using this dummy environment, services of our application have been tested for specific location and time, and the results are entirely satisfactory.

6.2.2 Simulation for All Other LBS Application Developers

________________________________________________________________________95

Page 99: Location and Time Based Information Exchange System

________________________________________________________________________A simulated positioning server has been developed which can be used by all other LBS application developers. For simulated positioning server two database relations have been made, one is used to store the predefined location information (Simulation Area Relation) and the second is used to store the current location of a device (Simulation Current Location Relation). Simulation Area Relation contains the permanent record of all the areas like Area Description, Min X, Max X, Min Y, Max Y. Simulation Current Location Relation will be filled by the tester17 and it contains IP Address, coordinates x, y. This coordinate is the exact point where the tester wants to check some of his services. The LBS application developers can check their applications for specific location by using this Simulated Position Server.

The most important aspect of this Simulated Position Server is that the format of request and response is exactly same as LaCoMoCo position server. For this type of input and output a servelet is developed. The request and response format for getting the position of a mobile device from LaCoMoCo and Simulated Position Server is given below:

Request to LaCoMoCo

“http://server_address/TrackServlet?value=x,y,z&clientId=192.168.100.102&measure=pixels”,

Response from LaCoMoCo

“3179.324480801351, 1325.092235752987, level4, 4.05”

Request to Simulated Position Server “http://servlet.itu.dk:8080/user/nadeem/servlet/TrackServlet?value=x,y,z&clientId=192.168.100.102&measure=pixels”Response from Simulated Position Server

“3179.324480801351, 1325.092235752987, level3, 4.05”

From the above two responses, it can be visualized that both the responses has same format. So LBS application developers can use Simulated Position Server which certainly provides consistent position results instead of using Ekahau Position Engine (LaCoMoCo).

17 Person or developer who wants to check his application against some predefined location________________________________________________________________________

96

Page 100: Location and Time Based Information Exchange System

________________________________________________________________________

7 Conclusions

In this thesis, first we have argued for providing different location based services on the basis of location and time, then the potential applicability of location and time bound services for a variety of indoor environments was discussed. Based on a review of the issue from a technological, as well as an implementation and cooperative perspective, we have developed the hypothesis that Location and time bound services offered by LTBIES can prove beneficial for many organizations in a number of application areas, such as supermarkets, museums, hospitals, hotels and multi-storey buildings. We have assessed the needs of a user in different organizational environments. We have also created different scenarios for a set of justified services for the deployment of LTBIES. To test the usability and usefulness of LTBIES, cooperative perspectives of LTBIES for different organizations is also discussed. As a result we have found answers to the important questions about its viability much more efficiently. We have explored why organizations would have such a system and probe how these services will be needed and fit in different scenarios. This analysis has produced valuable information for us about organizations and companies who are in need of systems like LTBIES.

Proposed set of services of LTBIES on the basis of location and time was only possible in the environment where the positioning technologies are installed to get the location of a mobile device. In LTBIES Ekahau Positioning Engine is used to get the location of mobile device. Quality of the location and time bound services provided by LTBIES heavily depends on the positioning engine. Ekahau Positioning Engine is not an accurate positioning engine and sometimes it tends to give location results with error. Therefore if the system gets wrong location from the positioning engine then the required quality of services will not be achieved. The accuracy problem of Ekahau Positioning Engine was overcome by the Simulated Position Server. This server has been developed to test the accuracy of LTBIES. This Simulated Position Server gives the reply for a position request in the same format as Ekahau Positioning Engine does with more consistency and accuracy. This simulation server can test the application for location.

LTBIES is using client system’s time and it could be wrong as a result message delivery can be affected; this inaccurate time can affect the quality of services. Solution to this problem is to make time of all systems

________________________________________________________________________97

Page 101: Location and Time Based Information Exchange System

________________________________________________________________________synchronized, so that the message delivery time remains same and wrong message delivery time can be controlled. To test time and location, simulation was also made to give the controlled time and location to the application.

Services that were proposed have been implemented successfully for indoor environment. These services are location and time bound. LTBIES application is developed by using Ekahau Positioning Engine, MySQL database server and java API. The java programming language has made it more robust and portable. The test results of LTBIES were satisfactory. Results directly form the positioning server and simulation are also compared to get the proof of application’s abilities and accuracy. It is also concluded that if the positioning engine gives the right location, then this application is capable to provide complete set of services perfectly.

Further Enhancements in LTBIES

Here we will discuss some points which could be used to add new services and to make the existing functionalities of LTBIES better, following points are important for future enhancement of the system:

Implementation on PDA Instead of Laptop

Although a system such as LTBIES may provide very handy services based on accurate location information of a mobile device of particular type (laptop), it alone is almost certainly not the ultimate choice of future end users. For more robustness it is needed that the system should be able to run on a variety of devices like PDAs and mobile phones.

Message delivery acknowledgement

A service of message delivery acknowledgement can be added to the system. After this addition user will be able to receive a receipt of delivered message.

________________________________________________________________________98

Page 102: Location and Time Based Information Exchange System

________________________________________________________________________Make a record of user’s location history

Another service which can be achieved is Surveillance. Surveillance can be done by keeping the records of user’s location as a history in the database. This record database can be used to find the activity of users at different locations in the past.

Shortest path guideline

The LTBIES can be expanded to become capable of finding the shortest path between different users or any destination of their interests, who are logged on to the system. This addition of shortest path will make LTBIES more dynamic. In the real world this feature will have a very positive impact on the users of the system they can find and reach each other at different destinations.

Location information

Location can be defined in more details by defining more physical context, like what is the use of room 3.19 what type of equipments it has.

Synchronized time

LTBIES is using client system’s time and it could be wrong as a result message delivery can be affected; this inaccurate time can affect the quality of services. To undermine this problem system can be enhanced to use server’s time. By doing this, all time bound services will be delivered according to the server’s synchronized time.

Acknowledgements

________________________________________________________________________99

Page 103: Location and Time Based Information Exchange System

________________________________________________________________________We would like to say Thanks to our supervisors Kåre Jelling Kristofferson and John Aasted Sørenson for their help, valuable comments and discussion for the successful completion of this project.

This project was very much a group development effort. We would like to acknowledge the support and help of all other groups during project period, the inspiring discussions we had with them along with the development of our work. Especial thanks goes to Anders Cervera who gave us a number of positive suggestions to provide us with the knowledge and help.

We would also like to thank to all of our friends and families who have

supported and helped us during the thesis period.

References

[Bacastow, 2002] Todd M. Bacastow, Dr. Fred Loomis: Progress Report, fall 2001, IST 496-Fall 2001, Revised 2002

________________________________________________________________________100

Page 104: Location and Time Based Information Exchange System

________________________________________________________________________

[Birkedal, 2002] Lars Birkedal, Kjeld Schmidt, and Peter Carstensen: Description CIT Project #313, Prepared by Crossroads Copenhagen, Version 2.2, 31 October 2002

[Cervera, 2003] Anders Cervera: Ekahau Positioning Server, IT University of Copenhagen, January 2003URL: http://positionserver.it-c.dk:8000/doc/WEB_API_040403.pdf

[Colulouris, 2001] George Colulouris, Jean Dollimore and Tim Kindberg: Distributed Systems - Concepts and Design, Addison-Wesley, 2001

[Ekahau, 2002] Ekahau: Configurations and system requirements, Ekahau positioning engine, 2002URL:http://www.ekahau.com/products/positioningengine/ClientReleaseNotes.html

[Ekahau, 2002] Ekahau: Ekahau positioning Engine- user guide, 2002URL: http://www.ekahau.com

[El-Akehal, 2003] Emad El-Dean El-Sayed El-Akehal: User Authentication and Information Exchange by Speech and Location Information in Mobile Systems, IT University of Copenhagen, August 2003

[Fishwick, 1999] Fishwick: The art and Science of Digital World Construction, August 1999

URL: http://www.cise.ufl.edu/~fishwick/introsim/paper.html

[Geier, 2002] Jim Geier: Ekahau Positioning Engine, URL: www.wi-fiplanet.com/reviews/SW/article.php/1560261

[IEC, 2003] International Engineering Consortium:URL: http://www.iec.org/online/tutorials/gsm/

[Korth, 1991] Henry F.Korth, Abraham Silberschatz: Database system concepts, Second edition, McGraw-hill Inc, 1991

[Kurose, 2002] James F. Kurose og Keith W. Ross: Computer Networking A Top-Down Approach Featuring the Internet, Addison-Wesley, 2002

[Lee, 2002] Richard C. Lee, William M. Tepfenhart: Practical Object Oriented Development with UML and Java, Prentice Hall, 2002

[Lynge, 2003] Thomas Lynge: Position Dependent Communication System, IT University of Copenhagen, June 2003

________________________________________________________________________101

Page 105: Location and Time Based Information Exchange System

________________________________________________________________________[Nerguizian, 2001] Chahe’ Nerguizian: A framework for Indoor Geolocation using an Intelligent System, 3rd WLAN workshop, 2001

URL: http://www.cwins.wpi.edu/wlans01/proceedings/wlan44d.pdf

[Pahlavan, 2002] Kaveh Pahlavan and Xinrong Li, Worcester Institute Juha-Pekka, University of Oulu, Finland: Indoor Geolocation Science and Technology, IEEE Communication Magazine, February 2002

[Petersen, 2003] Jonas E.Andersen and Bjørn E.Petersen: Geographic information Systems in context of Location Based Services, IT University of Copenhagen, May 2003

[Petrick, 1999] Bob O’Hara and Al Petrick: IEEE 802.11 Handbook A Designer Companion, Standard Information Network IEEE Press, December 1999

[Pressman, 2000] Roger S. Pressman: Software Engineering A practioner’s Approach, 5th edition, McGraw- Hill, April 2000

[Schmidt, 2003] Kjeld Schmidt: Global and Mobile Applications, Compendium, IT University of Copenhagen, Spring 2003

[Sørensen, 2002] John Aasted Sørensen: LaCoMoCo RWG meeting, Wireless 3D positioning, 31st October 2002.

[Sørensen, 2003] John Aasted Sørensen: Global and Mobile Application, Mobile positioning technology, 2003http://www.itu.dk/people/schmidt/teaching/gm/GM%235-6_positioning.pdf

[Tornado, 2003] Tornado insider names top 100 companies at Europe 2003 URL: http://www.tornado. insider.com/press/presses.asp?pressID=5470

[Turner, 2002] Anthony Turner: Mobile location services, 1st edition, McGraw- Hill Professional, June 2002

[Ullman, 2002] Hector Garcia-Molina, Jeff Ullman, and Jennifer Widom: Database Systems the Complete Book, Prentice Hall, 2002

[Virrantaus, 2001] Kirsi Virrantaus, Jouni Markkula, Artem Garmash, Vagan Terziyan, Jari Veijalanien, Artem Katanosov, Henri Tirri: Developing GIS-Spupported Location Based Services, University of Helsinki,Finland, Computer Society, 2001

[Watson, 2002] Richeard T.Watson: Data Management Databases and Orgnizations, Third edition,John Wiley & Sons,Inc,2002

________________________________________________________________________102

Page 106: Location and Time Based Information Exchange System

________________________________________________________________________[Yousaf, 2002] Moustafa A. Yousaf,Ashok Agrawala, A. Udaya Shankar, Sam H. Noh: A Probabilistic Clustering-Based Indoor Location Determination System, 2002

________________________________________________________________________103

Page 107: Location and Time Based Information Exchange System

________________________________________________________________________

Appendices

A1 User Manual

Before running this application the user has to make sure that his system has

the following components:

Java virtual machine. Install Java2 SDK (from version 1.4 and up). It can

be downloaded from http://java.sun.com/downloads/.

Ekahau client must be installed on the mobile terminal. It can be

downloaded from http://www.Ekahau.com/downloads/.

Wireless local area network (IEEE 802.11b standard)

LTBIES application software.

In order to run the LTBIES application, the user has to follow the following

steps

First run the server program

Run the client program

Now the user will get first welcome GUI. Select one of the three options

to get authentication from the server. In welcome interface the default

IP address of server will be given, one can change the IP address of

server if server is running on some other machine.

After getting authentication user get the main GUI, where he will be

allowed to avail all the services provided by the application.

A very short description of all these services is given below

Popup messages: when the user log on to the system, he will receive

pop up messages. These messages are those whose time and location

coincides with the predefined limit of location and time.

________________________________________________________________________104

Page 108: Location and Time Based Information Exchange System

________________________________________________________________________

My location: User can get his current position in the form (x, y, level, room). User can also request to view his position on map by the option SHOW ON MAP.

Messages: User can get text messages intended for him at current

location and also at specific time. The user can also send messages to

any other person or group at a specific location in the building at any

specific time.

Online persons: User can find the location of all connected users to

the system. The application also provides the location of other users on

any specific level (floor) by choosing floor number option.

Track person: This service is interested for those who want to track

the person by name (i.e. where is Mr. Bilal?). The application tracks the

requested person and shows the position of that person on map.

________________________________________________________________________105

Page 109: Location and Time Based Information Exchange System

________________________________________________________________________

A2 Abbreviation List

802.11b Registered trademark of the IEEEAP Access PointAPI Application Programming InterfaceBSC Base Station Controller BTS Base Transceiver Station EPE Ekahau Positioning Engine GSM Global System for Mobile CommunicationGPS Global Positioning SystemHTTP Hyper Text Transfer ProtocolIEEE The Institute of Electrical and Electronic EngineersITU IT University of CopenhagenJ2ME Java 2™ Micro EditionJ2SE Java 2™ Standard EditionJSDK Java Standard Development kitLaCoMoCo Laboratory for Context-dependent Mobile CommunicationLTBIES Location Based Information Exchange SystemMIDP Mobile Information Device ProfileMIDlet The J2ME™ Application.MSC Mobile Service Switching CentrePDA Personal Digital AssistantRF Radio FrequencyRTP Real Time ProtocolSIM Subscriber Identity Module TCP/IP Transmission Control Protocol/Internet ProtocolUML Unified Modelling LanguageURL Uniform Resource LocatorWi-Fi Wireless FidelityWLAN Wireless Local Area Network

________________________________________________________________________106

Page 110: Location and Time Based Information Exchange System

________________________________________________________________________

A3 UML Diagrams

UML, the unified modelling language, is a standard notation for modelling object oriented systems. It is a language that graphically described a set of elements. It is used to specify visualize, construct and document not only software systems but business models and non software systems. It is much like a blue print for constructing a building [Lee, 2002]. Some of the important UML diagrams of LTBIES are presented here.

________________________________________________________________________107

Page 111: Location and Time Based Information Exchange System

________________________________________________________________________

________________________________________________________________________108

Page 112: Location and Time Based Information Exchange System

________________________________________________________________________

________________________________________________________________________109

Page 113: Location and Time Based Information Exchange System

________________________________________________________________________

________________________________________________________________________110

Page 114: Location and Time Based Information Exchange System

________________________________________________________________________

________________________________________________________________________111

Page 115: Location and Time Based Information Exchange System

________________________________________________________________________

________________________________________________________________________112

Page 116: Location and Time Based Information Exchange System

________________________________________________________________________

________________________________________________________________________113

Page 117: Location and Time Based Information Exchange System

________________________________________________________________________

A4 Screen Shots

Figure (A4.1): First Graphical user interface

Figure (A4.2): Simulation test for time and location

________________________________________________________________________114

Page 118: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (A4.3): Guest login GUI

Figure (A4.4): Registered user login GUI

________________________________________________________________________115

Page 119: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (A4.5): My Location

Figure (A4.6): Registration form for new user

________________________________________________________________________116

Page 120: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (A4.7): Message services

Figure (A4.8): Track person by name

________________________________________________________________________117

Page 121: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (A4.9): Get messages from specific person or from all persons

Figure (A4.10): Leave messages to a particular person or specific group

________________________________________________________________________118

Page 122: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (A4.11): LTBIES Server

Figure (A4.12): List of all online persons

________________________________________________________________________119

Page 123: Location and Time Based Information Exchange System

________________________________________________________________________

Figure (A4.13): Main application graphical user interface

Figure (A4.14): Positions of tracked users on level 4

________________________________________________________________________120

Page 124: Location and Time Based Information Exchange System

________________________________________________________________________

A5 Database Tables

All the database tables with sample data

MESSAGE TABLE

C lien t

L og in

R eg ister

G u est

M ain M yL ocation

getM essage

Tra ck P erso n

O n lin eU sers

S h o w O n M a p A ll S h o w O n M a p

c lien tR ea d th rea d

m essa g eth rea d

L ocation

GROUP MEMBER

________________________________________________________________________121

Page 125: Location and Time Based Information Exchange System

________________________________________________________________________GROUP TABLE

LOCATION TABLE

USER TABLE

________________________________________________________________________122

Page 126: Location and Time Based Information Exchange System

________________________________________________________________________

A6 Program Listing

This application has been developed for Thesis project, as part of our Master degree program.

The application is for LBS WLAN positioning system. It runs on Mobile devices.

Participants: H.M.Bilal Sarwar : [email protected] Nadeem Ahmad : [email protected]

Shouket Iqbal : [email protected]

Supervisor: John Aasted Sørensen Kåre jelling Kristoffersen

IT University of Copenhagen.Novemebr 2003

The complete application software is provided in attached CD

________________________________________________________________________123

Page 127: Location and Time Based Information Exchange System

________________________________________________________________________A6.1 ClientWorker

package LTBIES.Server;

/** * <p> ClientWorker: </p> * <p>Server side class that deal with each client: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p>c * @author Nadeem, Bilal, Shouket * @version 1.0 */

import javax.swing.JTextArea;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.ImageIcon;import javax.swing.JLabel;import java.awt.event.WindowListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.Font;import java.awt.BorderLayout;import java.awt.Color;import java.io.*;import java.net.Socket;import java.net.ServerSocket;import java.util.HashMap;import java.util.StringTokenizer;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Driver;import java.sql.Statement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;class ClientWorker extends Thread { private Socket client; private JTextArea textArea; private String type; static String user; static HashMap userList =new HashMap() ;// username and ip static HashMap userMessage =new HashMap() ;// username and status to read database private BufferedReader in; static PrintWriter out; ClientWorker(Socket client, JTextArea textArea){ this.client = client; this.textArea = textArea; try{

in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true);} catch (IOException e) {}

________________________________________________________________________124

Page 128: Location and Time Based Information Exchange System

________________________________________________________________________

firstStep(); } public void run(){ while(true){ try{ String line=in.readLine();

StringTokenizer st=new StringTokenizer(line,"'"); if(st.hasMoreTokens()){

String t=st.nextToken(); if((t.equals("U"))||(t.equals("P"))){ String uList= userList.toString(); out.println("U"+uList);

} } userMessage.put(user,"true");

}catch(IOException ioex){ //System.out.print("ServerReadThread failed Removed element "); textArea.append("Mr. \" "+user+" \" is disconnected from the system "+"\n");

userMessage.remove(user); stop(); break; }

} } public void firstStep(){ String line;

boolean s=false; while(true){

try{ line = in.readLine(); //textArea.append("Connection request '"+line+"'\t"+" From Client "+ client.getInetAddress()); textArea.append("Connection request From User "); } catch (IOException e) { textArea.append("Read Write failed .... ");break; }

StringTokenizer st=new StringTokenizer(line,"'"); if(st.hasMoreTokens()){

type=st.nextToken();user=st.nextToken();textArea.append(": "+user+"\n");if(type.equals("G")){

//textArea.append(" as Guest"+"\n");String Q="SELECT userID from users where userID ="+"'"+user+"'";

s=query(Q);s=!s;

}else if(type.equals("L")){

//textArea.append(" to Login "+"\n");String pass=st.nextToken();

String Q="SELECT * from users where userID ="+" '"+user+"' and password= '"+pass+"'";s=query(Q);

}

________________________________________________________________________125

Page 129: Location and Time Based Information Exchange System

________________________________________________________________________

else if(type.equals("R")){//textArea.append(" to make a registration "+"\n");String insert=line.substring(1,line.length());String Q="INSERT INTO users VALUES("+insert+")";String pass=st.nextToken();s=UpdateQuery(Q);}

if(s){ if((userList.get(user))==null){

userList.put(user,client.getInetAddress()); userMessage.put(user,"false");

textArea.append(user+"'s Connection request is accepted"+"\n");out.println("true");WriteThread wt=new WriteThread();

wt.start();break;}else {

out.println("Name is allready in use");textArea.append(user+"'s Connection request is Rejected"+"\n");

} } else { out.println("Name is allready in use"); textArea.append(user+"'s Connection request is Rejected"+"\n"); } } } } public boolean query(String Q){ boolean b=false; try {

Class.forName("com.mysql.jdbc.Driver").newInstance();String username = "na_e2002";String password = "Eclipse";String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(Q);if(rs.next())b=true;stmt.close();rs=null;

}catch( Exception e ) {MySql record search query");

}return b;

} public boolean UpdateQuery(String Q){ boolean b=true; try {

Class.forName("com.mysql.jdbc.Driver").newInstance();String username = "na_e2002";String password = "Eclipse";String url = "jdbc:mysql://mysql.it-c.dk/" + username;

________________________________________________________________________126

Page 130: Location and Time Based Information Exchange System

________________________________________________________________________

Connection con = DriverManager.getConnection(url, username , password);Statement stmt = con.createStatement();stmt.executeUpdate(Q);stmt.close();}catch( Exception e ) {

b=false;return b;

}return b;

}

}

class WriteThread extends Thread{ public void run(){ while(true){ if(ClientWorker.userMessage.get(ClientWorker.user)=="true") print("D"); if(ClientWorker.userMessage.get(ClientWorker.user)=="true") print(“U”+userList”);

try{ sleep(2000);

}catch (InterruptedException e) {} } } public synchronized void print(String p){ ClientWorker.out.println(p); ClientWorker.userMessage.put(ClientWorker.user,"false"); } }class Server extends JFrame{

JTextArea textArea = new JTextArea(); ServerSocket server = null; Server(){ JPanel panel = new JPanel(); ImageIcon LTBIES_Server=new ImageIcon("LTBIES_Server.png"); ImageIcon Downtext=new ImageIcon("Downtext.png");

JLabel label = new JLabel(LTBIES_Server); Font font = new Font("Serif",Font.BOLD ,50);

label.setFont(font); JLabel label2 = new JLabel(Downtext); panel.setLayout(new BorderLayout()); panel.setBackground(new Color(211,106,1));//(Color.white); getContentPane().add(panel); panel.add("North", label); panel.add("Center", textArea); panel.add("South", label2);

________________________________________________________________________127

Page 131: Location and Time Based Information Exchange System

________________________________________________________________________ } //End Constructor public void listenSocket(){ try{ server = new ServerSocket(9786); } catch (IOException e) { System.exit(-1); } while(true){ ClientWorker w; try{ new ClientWorker(server.accept(), textArea).start(); } catch (IOException e) { } } }

protected void finalize(){ try{ server.close(); } catch (IOException e) { System.exit(-1); } }

public static void main(String[] args){ Server frame = new Server();

frame.setTitle("Location and Time Based Information Exchange System Server"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setSize(600,600); frame.setLocation(10,50); frame.setVisible(true); frame.listenSocket(); }}

________________________________________________________________________128

Page 132: Location and Time Based Information Exchange System

________________________________________________________________________A6.2 Location

package LTBIES.Client;

/** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * @author not attributable * @version 1.0 */

import java.util.*;import java.net.*;import java.io.*;

public class Location{private static String X,Y,Floor,Room;private static String URL_TXTRESPONSE,SERVER_IP="http://192.168.100.10:8000";//lapTop;String CLIENT_IP;Location(String ip){

this.CLIENT_IP=ip;URL_TXTRESPONSE= SERVER_IP+"/TrackServlet?

value=x,y,z&clientId="+CLIENT_IP+"&measure=pixels";getLocation();if(X==null){

SERVER_IP= "http://130.226.140.82:8000";//deskTopURL_TXTRESPONSE= SERVER_IP+"/TrackServlet?

value=x,y,z&clientId="+CLIENT_IP+"&measure=pixels";getLocation();

}

}public void getLocation( ) {

String str;StringBuffer lists = new StringBuffer();

try{ URL url = new URL(URL_TXTRESPONSE);

URLConnection connection = url.openConnection();InputStream in = connection.getInputStream();int i = 0;

while ((i = in.read()) != -1){ lists.append((char)i); } str=lists.toString(); in.close();

}catch (MalformedURLException mal){

str = mal.toString();}catch (IOException ioe) {

str = ioe.toString();}

________________________________________________________________________129

Page 133: Location and Time Based Information Exchange System

________________________________________________________________________

int counter=0;StringTokenizer st=new StringTokenizer(str,",");while(st.hasMoreTokens()){

st.nextToken();counter++;

}st=new StringTokenizer(str,",");if(counter==4){

X=st.nextToken();Y=st.nextToken();Floor=st.nextToken();Room=st.nextToken();

}

}

public int getX(){if(X!=null)return (new Double(Double.parseDouble(X)).intValue());elsereturn 0;

}public int getY(){

if(Y!=null)return (new Double(Double.parseDouble(Y)).intValue());elsereturn 0;

}public String getFloor(){

return Floor;}public String getRoom(){

return Room;//="3.19";}

public String toString(){return ("X:"+X+"\tY:"+Y+"\tRoom:"+Room+"\tFloor:"+Floor);

}}

________________________________________________________________________130

Page 134: Location and Time Based Information Exchange System

________________________________________________________________________A6.3 Client

package LTBIES.Client;

import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.net.*;import java.io.*;

public class Client{ static JFrame frame; static PrintWriter out = null; static BufferedReader in = null; JLabel message;

JTextField ipS; int port = 9786; static Socket socket; //String ip = "192.168.100.229"; //laptop String ip = "localhost"; //laptop Client() { Color bg = new Color(211, 106, 1); frame = new JFrame( "Location and Time Based Information Exchange System Ekahau"); frame.getContentPane().setLayout(new GridLayout(3, 3)); frame.setSize(600, 250); frame.setLocation(60, 50); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); //

ImageIcon labelImage = new ImageIcon("WELCOME_LTBIES.png"); ipS = new JTextField(ip); JLabel ipL = new JLabel("Server IP : "); JPanel BPanel, LPanel, panel; panel = new JPanel(); BPanel = new JPanel(); LPanel = new JPanel(); JLabel label = new JLabel(labelImage); Font font = new Font("Serif", Font.PLAIN, 30); label.setFont(font); message = new JLabel(); ImageIcon loginImage = new ImageIcon("Login_b.png"); ImageIcon regImage = new ImageIcon("Register_b.png"); ImageIcon guestImage = new ImageIcon("Guest_b.png"); JButton login, reg, guest; login = new JButton(loginImage); reg = new JButton(regImage); guest = new JButton(guestImage); login.setActionCommand("Login"); reg.setActionCommand("Register");

________________________________________________________________________131

Page 135: Location and Time Based Information Exchange System

________________________________________________________________________ guest.setActionCommand("Guest"); login.setBackground(new Color(253, 176, 102)); // reg.setBackground(new Color(253, 176, 102)); // guest.setBackground(new Color(253, 176, 102)); // welcomeListener listener = new welcomeListener(); login.addActionListener(listener); reg.addActionListener(listener); guest.addActionListener(listener); LPanel.add(label); BPanel.add(login); BPanel.add(reg); BPanel.add(guest); panel.add(ipL, BorderLayout.NORTH); panel.add(ipS, BorderLayout.CENTER); panel.add(message, BorderLayout.SOUTH); panel.setBackground(bg); BPanel.setBackground(bg); LPanel.setBackground(bg); frame.getContentPane().add(LPanel, BorderLayout.NORTH); frame.getContentPane().add(BPanel, BorderLayout.CENTER); frame.getContentPane().add(panel, BorderLayout.SOUTH); frame.getContentPane().setBackground(bg); listenSocket(); frame.setVisible(true); }

public static void main(String arg[]) { Client w = new Client(); }

public void listenSocket() { try { if (socket == null) { socket = new Socket(ipS.getText(), port); // socket.setSoTimeout( 5000 );

} } catch (UnknownHostException e) { System.out.println("Unknown host: "); message.setText("Unknown host: " + e); } catch (IOException e) { //System.out.println("No I/O "+e); message.setText("No I/O " + e); } } class welcomeListener implements ActionListener { public void actionPerformed(ActionEvent e) { //ip=ipS.getText(); listenSocket(); if (socket != null) { String command = e.getActionCommand(); if (command == "Login") {

________________________________________________________________________132

Page 136: Location and Time Based Information Exchange System

________________________________________________________________________ //System.out.println("i m in login state"); frame.setVisible(false); frame = null; Login l = new Login(socket); } else if (command == "Register") { //System.out.println("i m in Register state"); frame.setVisible(false); frame = null; Reg r = new Reg(socket); } else if (command == "Guest") { frame.setVisible(false); frame = null; Guest g = new Guest(); } } }

}}///CLASS////GUEST///////////////////////////////////////////////////////////class Guest{

JFrame frame;JLabel message;JTextField Tname;JButton submit,back;Guest( ){

gui();frame.setVisible(true);}private void gui(){Color bg=new Color(253,176,102);

frame=new JFrame("Location and Time Based Information Exchange System Ekahau");frame.getContentPane().setLayout(new GridLayout(5, 1));frame.setBackground(Color.blue);frame.setSize(450,250);frame.setLocation(60,50);

JLabel heading =new JLabel("Welcome as A Guest User"); Font font = new Font("Serif",Font.PLAIN,40);

heading.setFont(font); JLabel heading2 =new JLabel("Please Enter a User Name"); Font font2 = new Font("Serif",Font.PLAIN,30);

heading.setFont(font2);message =new JLabel(". . .");

Tname =new JTextField(15); submit=new JButton("Submit"); back=new JButton("Back");

Tname.setActionCommand("Submit"); submit.setActionCommand("Submit"); back.setActionCommand("Back");

guestListener listener=new guestListener(); submit.addActionListener(listener); back.addActionListener(listener);

________________________________________________________________________133

Page 137: Location and Time Based Information Exchange System

________________________________________________________________________ Tname.addActionListener(listener); JPanel panel1,panel2,panel3,panel4,panel5; panel1=new JPanel(); panel2=new JPanel(); panel3=new JPanel(); panel4=new JPanel(); panel5=new JPanel(); panel1.add(heading); panel2.add(heading2); panel3.add(Tname); panel4.add(submit); panel4.add(back); panel5.add(message); panel1.setBackground(bg); panel2.setBackground(bg); panel3.setBackground(bg); panel4.setBackground(bg); panel4.setBackground(bg); panel5.setBackground(bg); frame.getContentPane().add(panel1); frame.getContentPane().add(panel2); frame.getContentPane().add(panel3); frame.getContentPane().add(panel4); frame.getContentPane().add(panel5); try{

Client.out = new PrintWriter(Client.socket.getOutputStream(), true); Client.in = new BufferedReader(new

InputStreamReader(Client.socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host: "); } catch (IOException e) { System.out.println("No I/O "+e);}

frame.getContentPane().setBackground(bg);

}class guestListener implements ActionListener{

public void actionPerformed(ActionEvent e) {String command=e.getActionCommand();if(command=="Back"){

if(frame!=null){frame.setVisible(false);frame=null;Client c=new Client();

}}if(command=="Submit"){

if(Tname.getText().length()>2){connect();

if(frame!=null && message.getText().equals("true")){frame.setVisible(false);frame=null;

Main ma=new Main(Tname.getText(),"G",Client.socket);}

________________________________________________________________________134

Page 138: Location and Time Based Information Exchange System

________________________________________________________________________

else{message.setText("This name is already registered Please try with another name");Tname.setText(new String(""));

}}elsemessage.setText("Please Enter atleast three character");

}}

}private void connect(){ String text ="G'";

text+= Tname.getText(); Client.out.println(text ); try{

String line = Client.in.readLine(); message.setText(line);

//System.out.println("CLIENT...Text sended :" + line); }catch (IOException e){

System.out.println("READ failed"); }

}}class Login{

JFrame frame;JLabel heading,message;private JTextField Tname;private JPasswordField Tpassword;private JButton submit,back;;

String ip="localhost";Login(Socket socket){

gui();frame.setVisible(true);}private void gui(){

JPanel Hpanel,panel1,panel2,panel3,panel4;Color bg=new Color(253,176,102);

frame=new JFrame("Location and Time Based Information Exchange System Ekahau");frame.getContentPane().setLayout(new GridLayout(5, 1));frame.setSize(450,250);frame.setLocation(60,50);

frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); Hpanel=new JPanel(); panel1=new JPanel(); panel2=new JPanel(); panel3=new JPanel(); panel4=new JPanel(); submit=new JButton("Submit"); loginListener listener=new loginListener(); submit.addActionListener(listener);

________________________________________________________________________135

Page 139: Location and Time Based Information Exchange System

________________________________________________________________________

heading=new JLabel("User Login"); Font font = new Font("Serif",Font.PLAIN,30);

heading.setFont(font); JLabel Lname=new JLabel("User Name");

JLabel Lpassword=new JLabel("Password"); Tname=new JTextField(15); Tpassword=new JPasswordField(15); message=new JLabel(); back=new JButton(" Back "); back.addActionListener(listener); Tname.addActionListener(listener); Tpassword.addActionListener(listener); Tname.setActionCommand("Submit"); Tpassword.setActionCommand("Submit"); submit.setActionCommand("Submit"); back.setActionCommand("Back"); Hpanel.add(heading); panel1.add(Lname); panel1.add(Tname); panel2.add(Lpassword); panel2.add(Tpassword); panel3.add(submit); panel3.add(back); panel4.add(message); Hpanel.setBackground(bg); panel1.setBackground(bg); panel2.setBackground(bg); panel3.setBackground(bg); panel4.setBackground(bg); frame.getContentPane().setBackground(bg); frame.getContentPane().add(Hpanel); frame.getContentPane().add(panel1); frame.getContentPane().add(panel2); frame.getContentPane().add(panel3); frame.getContentPane().add(panel4); try{

Client.out = new PrintWriter(Client.socket.getOutputStream(), true); Client.in = new BufferedReader(new

InputStreamReader(Client.socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host: "); } catch (IOException e) { System.out.println("No I/O "+e); }

}

public void connect(){ String text ="L'";

text+= Tname.getText()+"'"; text+= Tpassword.getText(); Client.out.println(text );

try{

________________________________________________________________________136

Page 140: Location and Time Based Information Exchange System

________________________________________________________________________

String line = Client.in.readLine(); if(line.equals("true")){ Main ma=new Main(Tname.getText(),"L",Client.socket); if(frame!=null){

frame.setVisible(false);frame=null;}

} else{ Tname.setText("");

Tpassword.setText(""); message.setText("Not a valied login..Please try again.");

} }catch (IOException e){

System.out.println("READ failed"); }

}

class loginListener implements ActionListener{public void actionPerformed(ActionEvent e) {

String command=e.getActionCommand();System.out.println(command);if(command=="Submit"){

connect();}if(command=="Back"){

if(frame!=null){frame.setVisible(false);frame=null;Client c=new Client();

}}

}}

}class Reg{

private JFrame fram;private JLabel message;private JTextField TUname,TFname,TLname,Tlogin,Tpass,Temail;JButton submit,clear,back;int port=9786;Reg(Socket socket){

gui();fram.setVisible(true);}private void gui(){

Color bg=new Color(253,176,102);fram=new JFrame("Location and Time Based Information Exchange System Ekahau");

fram.getContentPane().setLayout(new GridLayout(8, 1));fram.setSize(700,450);fram.setLocation(60,50);

fram.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);

________________________________________________________________________137

Page 141: Location and Time Based Information Exchange System

________________________________________________________________________

} });

JLabel heading,LUname,LFname,LLname,Llogin,Lpass,Lemail,message; heading=new JLabel("User Registration"); Font font = new Font("Serif",Font.PLAIN,40);

heading.setFont(font);message=new JLabel("");

LUname=new JLabel("User ID"); LFname=new JLabel("First Name"); LLname=new JLabel("Last Name"); Lpass=new JLabel("Password"); Lemail=new JLabel("E-mail"); TUname=new JTextField(15); TFname=new JTextField(15); TLname=new JTextField(15); Tpass=new JTextField(10); Temail=new JTextField(30); submit=new JButton("Submit"); clear=new JButton("Clear"); back=new JButton("Back"); regListener listener=new regListener(); submit.addActionListener(listener); clear.addActionListener(listener); back.addActionListener(listener);

JPanel panel0,panel1,panel2,panel3,panel4,panel5,panel6,panel7,panel; panel0=new JPanel(); panel1=new JPanel(); panel2=new JPanel(); panel3=new JPanel(); panel4=new JPanel(); panel5=new JPanel(); panel6=new JPanel(); panel7=new JPanel(); panel=new JPanel(); panel0.add(heading); panel1.add(LUname); panel1.add(TUname); panel2.add(LFname); panel2.add(TFname); panel3.add(LLname); panel3.add(TLname); panel5.add(Lpass); panel5.add(Tpass); panel6.add(Lemail); panel6.add(Temail); panel7.add(submit); panel7.add(clear); panel7.add(back); panel.add(message); panel.setBackground(bg); panel0.setBackground(bg); panel1.setBackground(bg); panel2.setBackground(bg);

________________________________________________________________________138

Page 142: Location and Time Based Information Exchange System

________________________________________________________________________

panel3.setBackground(bg);panel5.setBackground(bg);

panel6.setBackground(bg); panel7.setBackground(bg); fram.getContentPane().setBackground(bg); fram.getContentPane().add(panel0); fram.getContentPane().add(panel1); fram.getContentPane().add(panel2); fram.getContentPane().add(panel3); fram.getContentPane().add(panel5); fram.getContentPane().add(panel6); fram.getContentPane().add(panel7); fram.getContentPane().add(panel); try{

Client.out = new PrintWriter(Client.socket.getOutputStream(), true); Client.in = new BufferedReader(new

InputStreamReader(Client.socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host: "); } catch (IOException e) { System.out.println("No I/O "+e); }}

class regListener implements ActionListener{public void actionPerformed(ActionEvent e) {

String command=e.getActionCommand();if(command=="Submit"){

String insert="R'"+TFname.getText()+"','"+TLname.getText()+"','"+Temail.getText();insert+="','"+TUname.getText()+"','"+Tpass.getText()+"'";System.out.println("Query is "+insert);Client.out.println(insert );try{

System.out.println("waiting to get responce from server"); String line = Client.in.readLine(); System.out.println("CLIENT...Text sended :" + line); System.out.println("linbe is "+line);if(line.equals("true")){ fram.setVisible(false); fram=null; Main ma=new Main(TUname.getText(),"G",Client.socket);

}elsemessage.setText("It is not a valid record please try again");

}catch (IOException ee){System.out.println("READ failed");}}if(command=="Clear"){System.out.println("i m in CLEAR button command of RegistRATION");

TUname.setText("");TFname.setText("");TLname.setText("");Tlogin.setText("");

________________________________________________________________________139

Page 143: Location and Time Based Information Exchange System

________________________________________________________________________

Tpass.setText("");Temail.setText("");

}if(command=="Back"){

System.out.println("i m in BACK button command of RegistRATION");fram.setVisible(false);fram=null;Client c=new Client();

} }

} }

________________________________________________________________________140

Page 144: Location and Time Based Information Exchange System

________________________________________________________________________A6.4 Main

package LTBIES.Client;

import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.io.*;import java.net.*;import java.util.*;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Driver;import java.sql.Statement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;

import java.text.*;import javax.swing.border.*;

public class Main{ static JFrame frame; static HashMap userList = new HashMap(); static HashMap messageList = new HashMap(); JButton myLocationB, message, onlineUsers, traceUsers; JPanel panel; JButton exit; static myLocation ml; static JTextArea messages; static JPanel field; Socket socket; static String user, type; PrintWriter out = null; BufferedReader in = null; mainListener listener;

Main(String user, String type, Socket socket) { this.socket = socket; this.user = user; this.type = type; try { out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host: " + socket); } catch (IOException e) { System.out.println("No I/O " + e); }

frame = new JFrame( "Location and Time Based Information Exchange System Ekahau");

________________________________________________________________________141

Page 145: Location and Time Based Information Exchange System

________________________________________________________________________ frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().setBackground(new Color(211, 106, 1));

JLabel heading = new JLabel( "Welcome to Location & Time Based Information Exchange System"); ImageIcon image = new ImageIcon("header.png");

heading = new JLabel(image);

Font font = new Font("Serif", Font.PLAIN, 35); JLabel heading2 = new JLabel(" "); heading2.setFont(font);

panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

frame.setSize(960, 650); frame.setLocation(55, 40); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });

ImageIcon myLocationImage = new ImageIcon("MyLocation.png"); ImageIcon messageImage = new ImageIcon("Messages.png"); ImageIcon onlineUsersImage = new ImageIcon("Avaiable.png"); ImageIcon traceUsersImage = new ImageIcon("Track.png"); ImageIcon exitImage = new ImageIcon("Exit.png");

myLocationB = new JButton(myLocationImage); message = new JButton(messageImage); onlineUsers = new JButton(onlineUsersImage); traceUsers = new JButton(traceUsersImage); exit = new JButton(exitImage);

myLocationB.setBackground(new Color(253, 176, 102)); // message.setBackground(new Color(253, 176, 102)); // onlineUsers.setBackground(new Color(253, 176, 102)); // traceUsers.setBackground(new Color(253, 176, 102)); // exit.setBackground(new Color(253, 176, 102)); //

myLocationB.setActionCommand("My Location"); message.setActionCommand("Messages"); onlineUsers.setActionCommand("Online Users"); traceUsers.setActionCommand("Track Person"); exit.setActionCommand("exit");

listener = new mainListener();

myLocationB.addActionListener(listener); message.addActionListener(listener); onlineUsers.addActionListener(listener);

________________________________________________________________________142

Page 146: Location and Time Based Information Exchange System

________________________________________________________________________ traceUsers.addActionListener(listener); exit.addActionListener(listener); panel.setBackground(new Color(253, 176, 102)); panel.add(Box.createRigidArea(new Dimension(0, 50))); panel.add(myLocationB); panel.add(Box.createRigidArea(new Dimension(10, 10))); panel.add(message); panel.add(Box.createRigidArea(new Dimension(10, 10))); panel.add(onlineUsers); panel.add(Box.createRigidArea(new Dimension(10, 10))); panel.add(traceUsers); panel.add(Box.createRigidArea(new Dimension(10, 10))); panel.add(exit);

ImageIcon imageB = new ImageIcon("button2.png"); JButton tryB = new JButton(imageB);

field = new JPanel(); messages = new JTextArea("\n Mr. " + user + " Welcome to Location and Time \n Based information Exchange System "); //Font font = new Font("Serif",Font.PLAIN,35); messages.setFont(font); field.setBackground(new Color(250, 250, 250)); field.add(messages);

frame.getContentPane().add(heading, BorderLayout.NORTH); frame.getContentPane().add(panel, BorderLayout.WEST);

frame.getContentPane().add(field, BorderLayout.CENTER); frame.getContentPane().add(heading2, BorderLayout.SOUTH); new ClientReadThread(in).start(); new messagesThread().start(); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F');

JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); JMenuItem mylocationFM = new JMenuItem("My Location", 'L'); JMenuItem messageFM = new JMenuItem("Messages", 'M'); JMenuItem onlineFM = new JMenuItem("Online Users", 'U'); JMenuItem trackFM = new JMenuItem("Track Person", 'T'); JMenuItem Exit = new JMenuItem("Exit", 'x');

JMenuItem aboutUs = new JMenuItem("About Us", 'U'); JMenuItem aboutApp = new JMenuItem("About Application", 'A');

mylocationFM.setActionCommand("My Location"); messageFM.setActionCommand("Messages"); onlineFM.setActionCommand("Online Users"); trackFM.setActionCommand("Track Person"); Exit.setActionCommand("exit");

________________________________________________________________________143

Page 147: Location and Time Based Information Exchange System

________________________________________________________________________ aboutUs.setActionCommand("aboutUs"); aboutApp.setActionCommand("aboutApp");

mylocationFM.addActionListener(listener); messageFM.addActionListener(listener); onlineFM.addActionListener(listener); trackFM.addActionListener(listener); Exit.addActionListener(listener);

aboutUs.addActionListener(listener); aboutApp.addActionListener(listener);

fileMenu.add(mylocationFM); fileMenu.add(messageFM); fileMenu.add(onlineFM); fileMenu.add(trackFM); fileMenu.add(Exit);

helpMenu.add(aboutUs); helpMenu.add(aboutApp);

menuBar.setBackground(new Color(253, 176, 102)); menuBar.add(fileMenu); menuBar.add(helpMenu); frame.setJMenuBar(menuBar);

frame.setVisible(true); }

class mainListener implements ActionListener { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "My Location") { field.removeAll(); messages.setText(" My Location "); if (ml == null) { ml = new myLocation(user); } field.setLayout(new GridLayout(1, 1)); field.add(ml); Graphics gra = field.getGraphics(); field.paintAll(gra); } if (command == "Messages") { field.removeAll(); JPanel messageMenu = new JPanel(); JPanel messageMenu1 = new JPanel(); JPanel messageMenu2 = new JPanel(); JPanel messageMenu3 = new JPanel();

JLabel messageLabel = new JLabel("Select One of Them to Proceed "); messageLabel.setFont(new Font("Serif", Font.PLAIN, 40));

JButton getMessages = new JButton("Get Messages");

________________________________________________________________________144

Page 148: Location and Time Based Information Exchange System

________________________________________________________________________ JButton leaveMessage = new JButton("Leave Message");

getMessages.addActionListener(listener); leaveMessage.addActionListener(listener);

messageMenu.setLayout(new GridLayout(3, 1, 1, 1));

messages.setText(" Messages"); messageMenu1.add(messageLabel); messageMenu2.add(getMessages); messageMenu2.add(leaveMessage); messageMenu.add(messageLabel); messageMenu.add(getMessages); messageMenu.add(leaveMessage);

field.removeAll(); field.add(messageMenu); Graphics gra = field.getGraphics(); field.paintAll(gra); frame.setVisible(true);

} if (command == "Online Users") { out.println("U'Online Users"); messages.setText(" Online Users "); field.removeAll(); onlineUsers online = new onlineUsers(userList); field.add(online); Graphics gra = field.getGraphics(); field.paintAll(gra);

} if (command == "Event Info") { field.removeAll(); messages.setText(" Event Info "); Graphics gra = field.getGraphics(); field.paintAll(gra); frame.setVisible(true); } if (command == "Track Person") { out.println("P'Track 'Users'"); field.removeAll(); messages.setText(" Trace Users "); trackPerson tp = new trackPerson(user); field.add(tp); Graphics gra = field.getGraphics(); field.paintAll(gra); } if (command == "Get Messages") { field.removeAll(); getMessage gm = new getMessage(user); Graphics gra = field.getGraphics(); field.add(gm); field.paintAll(gra);

________________________________________________________________________145

Page 149: Location and Time Based Information Exchange System

________________________________________________________________________

} if (command == "Leave Message") { field.removeAll(); leavMessageForm lmf = new leavMessageForm(out, user); field.add(lmf, BorderLayout.SOUTH); Graphics gra = field.getGraphics(); field.paintAll(gra); } if (command == "icon Button") { } if (command == "exit") { frame.setVisible(false); frame = null; System.exit(0);

} if (command == "aboutUs") { // System.out.println(" aboutUs Button is pressed : "+command); } if (command == "aboutApp") { // System.out.println("aboutApp Button is pressed : "+command); }

} }}

class ClientReadThread extends Thread {BufferedReader in=null;

ServerSocket server; ClientReadThread(BufferedReader in) { this.in=in; } public void run(){ while(true){ try{ String line=in.readLine(); if(line.substring(0,1).equals("U")){ Main.userList.clear();

line=line.substring(2,line.length()-1);StringTokenizer st=new StringTokenizer(line,",");while(st.hasMoreTokens()){StringTokenizer st2=new StringTokenizer(st.nextToken(),"=/");String n=st2.nextToken().trim();String i=st2.nextToken().trim();

Main.userList.put(n,i);}

}else System.out.println("it is not user ælist "+line); }catch(IOException ioex){System.out.println("out from read thread"+ioex);break;}

} }

________________________________________________________________________146

Page 150: Location and Time Based Information Exchange System

________________________________________________________________________

}class messagesThread extends Thread{

SimulationForm SF;String ip;String Cip;String areaID;String room;

messagesThread(){SF=new SimulationForm(Main.user);

}

public void run(){try{

String ip=InetAddress.getLocalHost().toString();String Cip=ip.toString();Cip=Cip.substring(1,Cip.length());

}catch(IOException ioe){}Location loc=new Location(Cip);while(true){

room=loc.getRoom();if(SF.getArea()!="null")

room=SF.getArea();query(room);try{

sleep(1000);}catch (InterruptedException e) {}

}}

public void query(String room){ try {Class.forName("com.mysql.jdbc.Driver").newInstance();

String username = "na_e2002";String password = "Eclipse";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd hh:mm:ss "); Date date=new Date(); String sT=sdf.format(date);

sT=SF.getTime(); String Q="SELECT * FROM `messages` where mTo='All' or mTo='"+Main.user+"' and areaID ='"+room+"' and sTime < '"+sT+"' and eTime >'"+sT+"'"; if(areaID!=null){ ResultSet rs = stmt.executeQuery(Q); while (rs.next()) { String message = rs.getString("message"); String subject = rs.getString("subject"); String mFrom = rs.getString("mFrom"); String messageID = rs.getString("messageID"); String send = mFrom + ",,,,," + subject + ",,,,," + message; String mes = ""; if (Main.messageList.get(messageID) == null) { int i = 0; if (message.length() > 50) {

________________________________________________________________________147

Page 151: Location and Time Based Information Exchange System

________________________________________________________________________ for (; i + 50 < message.length(); i = i + 50) mes += message.substring(i, i + 50) + "\n"; mes += message.substring(i, message.length()); } else mes = message; JFrame jf = new JFrame("PopUp Message"); jf.getContentPane().setLayout(new GridLayout(4, 1)); jf.getContentPane().add(new JLabel(" Message From : " + mFrom)); jf.getContentPane().add(new JLabel(" Subject : " + subject)); jf.getContentPane().add(new JLabel(" Message : ")); jf.getContentPane().add(new JTextArea(mes)); jf.setSize(300, 200); Main.messageList.put(messageID, mFrom); jf.setVisible(true); //System.out.println(" Sended Message "+send); } } }

stmt.close();}catch( Exception e ) {

System.out.println(" Exception Occured in MySql message search query");}

}}

class myLocation extends JPanel{private JTextField X,Y,Floor,Room;JButton onMap;Location Loc;String CLIENT_IP,user;myLocation(String user){

this.user=user;Color bg=new Color(191,223,255);

JPanel panel1,panel2,panel3,panel4,panel5;try{String cip =InetAddress.getLocalHost().toString();System.out.println("cip is "+cip);StringTokenizer st=new StringTokenizer(cip,"/");while(st.hasMoreTokens()){CLIENT_IP=st.nextToken();}System.out.println("cip is "+CLIENT_IP);}catch(IOException ioe){}setLayout(new GridLayout(5,3));JLabel lX,lY,lFloor,lRoom;lX=new JLabel(" X :");lY=new JLabel(" Y :");lFloor=new JLabel(" Floor");lRoom=new JLabel(" Room");X=new JTextField("D 311.11119",20);Y=new JTextField("D 234.56789",20);Floor=new JTextField("D 3rd",20);

________________________________________________________________________148

Page 152: Location and Time Based Information Exchange System

________________________________________________________________________

Room=new JTextField("D 3.19",20);onMap=new JButton(new ImageIcon("onMap.png"));onMap.setActionCommand("Show on Map");//new ImageIcon("header.png");onMap.setBackground(bg);onMapListener listener=new onMapListener();onMap.addActionListener(listener);panel1=new JPanel();panel2=new JPanel();panel3=new JPanel();panel4=new JPanel();panel5=new JPanel();panel1.add(lX);panel1.add(X);panel2.add(lY);panel2.add(Y);panel3.add(lFloor);panel3.add(Floor);panel4.add(lRoom);panel4.add(Room);panel5.add(onMap);add(panel1);add(panel2);add(panel3);add(panel4);add(panel5);

panel1.setBackground(bg); panel2.setBackground(bg); panel3.setBackground(bg); panel4.setBackground(bg); panel5.setBackground(bg);

locThread loc=new locThread();loc.start();}

class locThread extends Thread{locThread(){

Loc=new Location(CLIENT_IP);getLoc();

}public void run(){

while(true){try{

getLoc();sleep(2000);

}catch (InterruptedException e) {}}

}public void getLoc(){

if(!(Room.getText().equals(Loc.getRoom()))){X.setText(String.valueOf(Loc.getX()));Y.setText(String.valueOf(Loc.getY()));Floor.setText(Loc.getFloor());Room.setText(Loc.getRoom());

}

________________________________________________________________________149

Page 153: Location and Time Based Information Exchange System

________________________________________________________________________

}}class trackPerson extends JPanel{

JComboBox CList;ImageIcon map;String user;

trackPerson(String user){this.user=user;CList=new JComboBox();

JLabel label=new JLabel(" Track Person ");JLabel label2=new JLabel("Select the name of a person to be Tracked");JButton go=new JButton("Go");JLabel message=new JLabel(" ");

Font font = new Font("Serif",Font.PLAIN,35);label.setFont(font);

tarckPersonListener listener=new tarckPersonListener(); go.addActionListener(listener);

JPanel panel1=new JPanel();JPanel panel2=new JPanel();JPanel panel3=new JPanel();JPanel panel4=new JPanel();JPanel panel5=new JPanel();panel1.add(label);panel2.setLayout(new GridLayout(1,2));panel2.add(CList);panel2.add(go);panel2.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"Select the

name of a person to be Tracked", TitledBorder.LEFT, TitledBorder.TOP, new Font ("Serif", Font.ITALIC, 20), Color.blue));

panel3.add(message);panel4.setLayout(new GridLayout(3,1));panel4.add(panel1);panel4.add(panel2);panel4.add(panel3);

setLayout(new BorderLayout()); add(panel4,BorderLayout.NORTH);

fillCList(); } private void fillCList(){ CList.removeAllItems();

Set set=Main.userList.keySet();Iterator iter=set.iterator();while(iter.hasNext())

CList.addItem(iter.next());}class tarckPersonListener implements ActionListener{

public void actionPerformed(ActionEvent e) {String command=e.getActionCommand();if(command=="Go"){

________________________________________________________________________150

Page 154: Location and Time Based Information Exchange System

________________________________________________________________________

String ip=(String)Main.userList.get((String)CList.getSelectedItem());showOnMap show=new

showOnMap((String)CList.getSelectedItem(),ip);

}}

}}

________________________________________________________________________151

Page 155: Location and Time Based Information Exchange System

________________________________________________________________________A6.5 getMessage

package LTBIES.Client;

import java.awt.Color;import java.awt.BorderLayout;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.text.*;import java.awt.*;

import java.io.*;import java.net.*;

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Driver;import java.sql.Statement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import javax.swing.border.*;

public class getMessage extends JPanel{JComboBox Cfrom,Cdate;JButton submit;String user;CustomScrollPane sp;JTextArea text;getMessage(String user){

this.user=user;Color bg=new Color(191,223,255);//setLayout(new GridLayout(5,1));Font font = new Font("Serif",Font.PLAIN,40);JLabel label=new JLabel("Get Messages");label.setFont(font);JLabel from=new JLabel("From : ");JLabel date=new JLabel("Date : ");text=new JTextArea("Messages will come here ");submit=new JButton("Click");getMessageListener listener=new getMessageListener();submit.addActionListener(listener);JPanel panel1=new JPanel();JPanel panel2=new JPanel();JPanel panel3=new JPanel();JPanel panel4=new JPanel();JPanel panel5=new JPanel();this.setBackground(bg);panel1.setBackground(bg);

panel2.setBackground(bg); panel3.setBackground(bg); panel4.setBackground(bg);

________________________________________________________________________152

Page 156: Location and Time Based Information Exchange System

________________________________________________________________________ panel5.setBackground(bg);

Cfrom=new JComboBox();Cdate=new JComboBox();panel1.add(label);panel2.add(from);panel2.add(Cfrom);panel2.add(date);panel2.add(Cdate);panel3.add(submit);panel5.setLayout(new GridLayout(3,1));panel5.add(panel1);panel5.add(panel2);panel5.add(panel3);panel4.add(text);panel5.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"",

TitledBorder.LEFT, TitledBorder.TOP, new Font ("Serif", Font.ITALIC, 10), Color.blue)); panel4.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"Messages", TitledBorder.LEFT, TitledBorder.TOP, new Font ("Serif", Font.ITALIC, 20), Color.blue)); sp = new CustomScrollPane(panel4);

this.add(panel5);this.add(sp);fillCombo();

}private void fillCombo(){

try {Class.forName("com.mysql.jdbc.Driver").newInstance();

String username = "na_e2002";String password = "Eclipse";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);Statement stmt = con.createStatement();SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd hh:mm:ss ");

Date date=new Date(); String sT=sdf.format(date);

Cfrom.addItem("All");String Q="SELECT userID FROM `users`";ResultSet rs = stmt.executeQuery(Q);while( rs.next() ){

Cfrom.addItem(rs.getString("userID"));}

stmt.close();}catch( Exception e ) {

System.out.println(e.getMessage());e.printStackTrace();System.out.println("Exception S O O R Y ");

________________________________________________________________________153

Page 157: Location and Time Based Information Exchange System

________________________________________________________________________

}SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

Date date=new Date(); for(int i=0;i<7;i++){ String s=sdf.format(date); Cdate.addItem(s); date.setDate(date.getDate()-1); }

}public class getMessageListener implements ActionListener{

public void actionPerformed(ActionEvent e) {String command=e.getActionCommand();if(command=="Click"){

Date date=new Date();SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");SimpleDateFormat formatter= new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");

String today=sdf.format(date);String qDate=(String)Cdate.getSelectedItem();String qDateS=new String(qDate+" 00:00:00");if(today.equals(qDate)){

qDate=formatter.format(new Date());}else{

qDate=qDate+" 23:59:59";}

String Q="SELECT * from messages where mTo='"+user+"' or mTo='All' and ";if(!(Cfrom.getSelectedItem().equals("All"))){

Q+=" mFrom ='"+Cfrom.getSelectedItem()+"' and ";}Q+=" eTime >= ' "+qDateS+"'";Q+="and sTime <= ' "+qDate+"'";query(Q);}

}private void query(String Q){try {Class.forName("com.mysql.jdbc.Driver").newInstance();

String username = "na_e2002";String password = "Eclipse";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(Q);text.setText("");if( rs.next()){do{String message = rs.getString("message");

String subject = rs.getString("subject");String mFrom = rs.getString("mFrom");String mes="Message From : "+mFrom+"\nSubject : "+subject;mes+="\nMessage : \n";int i=0;

for(;i+50<message.length();i=i+50)

________________________________________________________________________154

Page 158: Location and Time Based Information Exchange System

________________________________________________________________________

mes+=message.substring(i,i+50)+"\n";mes+=message.substring(i,message.length());mes+="\n-------------------------------------------\n";text.append(mes+"\n");}while( rs.next() );}elsetext.setText("\n There is no any Message \n");stmt.close();}catch( Exception e ) {e.printStackTrace();System.out.println("Exception S O O R Y ");}}

}}

________________________________________________________________________155

Page 159: Location and Time Based Information Exchange System

________________________________________________________________________A6.6 leavMessageForm

package LTBIES.Client;

import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.text.*;import java.util.*;import java.net.*;import java.io.*;

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Driver;import java.sql.Statement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import javax.swing.border.*;

public class leavMessageForm extends JPanel{static JFrame fram;

static JTextField Tsubject,TareaID,TsTime,TeTime,TmTo;static JTextArea Tmessage;private JButton submit,clear,back;PrintWriter out = null;String user;private JComboBox comboMto,comboLocation;private JComboBox sH,sM,sD,eH,eM,eD;JLabel errorMessage;

leavMessageForm(PrintWriter out,String user){this.out=out;this.user=user;

JPanel panel0,panel1,panel2,panel3,panel4,panel5,panel6,panel7,panel8; JLabel heading,LmTo,LareaID,Lsubject,LsTime,LeTime,Lmessage; JLabel Lh,Lm,Ld;

comboMto=new JComboBox();comboLocation=new JComboBox();

sH=new JComboBox();sM=new JComboBox();sD=new JComboBox();eH=new JComboBox();eM=new JComboBox();eD=new JComboBox();

fillComboBox();fillTime();

Lh=new JLabel("Hours:");

________________________________________________________________________156

Page 160: Location and Time Based Information Exchange System

________________________________________________________________________

Lm=new JLabel("Minutes:");Ld=new JLabel("Date:");errorMessage=new JLabel("");

heading=new JLabel(" LEAVE MESSAGE "); Font font = new Font("Serif",Font.PLAIN,40);

heading.setFont(font);

LmTo=new JLabel("Message To: "); Lsubject=new JLabel("Subject:"); LareaID=new JLabel("Location: "); LsTime=new JLabel("Start Time: "); LeTime=new JLabel("End Time: "); Lmessage=new JLabel("Message: ");

TmTo=new JTextField(15); Tsubject=new JTextField(15); TareaID=new JTextField(15);

TsTime=new JTextField(10); TeTime=new JTextField(10); Tmessage=new JTextArea(5,40); back=new JButton("Back"); submit=new JButton(new ImageIcon("Submit.png")); clear=new JButton(new ImageIcon("clear.png")); submit.setActionCommand("Submit"); clear.setActionCommand("Clear"); regListener listener=new regListener(); submit.addActionListener(listener); clear.addActionListener(listener); back.addActionListener(listener); panel0=new JPanel(); panel1=new JPanel(); panel2=new JPanel(); panel3=new JPanel(); panel4=new JPanel(); panel5=new JPanel(); panel6=new JPanel(); panel7=new JPanel(); panel8=new JPanel(); panel0.add(heading); panel1.setLayout(new GridLayout(3,2)); panel1.add(LmTo); panel1.add(comboMto); panel1.add(Lsubject); panel1.add(Tsubject); panel1.add(LareaID); panel1.add(comboLocation); panel2.setLayout(new GridLayout(2,1)); panel2.add(panel0); panel2.add(panel1); panel3.add(LsTime); panel3.add(new JLabel("Hours:")); panel3.add(sH);

________________________________________________________________________157

Page 161: Location and Time Based Information Exchange System

________________________________________________________________________ panel3.add(new JLabel("Minutes:")); panel3.add(sM); panel3.add(new JLabel("Date:")); panel3.add(sD); panel4.add(LeTime); panel4.add(Lh); panel4.add(eH); panel4.add(Lm); panel4.add(eM); panel4.add(Ld); panel4.add(eD); JPanel timePanel=new JPanel(); timePanel.setLayout(new GridLayout(2,1)); timePanel.add(panel3); timePanel.add(panel4); timePanel.setBorder(new TitledBorder( LineBorder.createBlackLineBorder()," Time Period to deliver the Message", TitledBorder.LEFT, TitledBorder.TOP, new Font ("Serif", Font.ITALIC, 20), Color.blue)); JPanel ePanel=new JPanel(); ePanel.add(errorMessage); panel5.add(Lmessage); panel5.add(Tmessage); timePanel.setLayout(new GridLayout(2,1)); panel6.add(submit); panel6.add(clear); panel6.add(ePanel); setLayout(new GridLayout(5,2,1,1));

setBackground(Color.white); add(panel2); add(timePanel); add(panel5); add(panel6);

}

public class regListener implements ActionListener{public void actionPerformed(ActionEvent e) {

String command=e.getActionCommand();

if(command=="Submit"){Date date=new Date();boolean ok=false;Date endDate=new Date();Date startDate=new Date();String startTime=(String)sD.getSelectedItem();startTime+=" "+sH.getSelectedItem();startTime+=":"+sM.getSelectedItem()+":00";String endTime=(String)eD.getSelectedItem();endTime+=" "+eH.getSelectedItem();endTime+=":"+eM.getSelectedItem()+":00";

SimpleDateFormat formatter= new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");try{

________________________________________________________________________158

Page 162: Location and Time Based Information Exchange System

________________________________________________________________________

startDate=formatter.parse(startTime);endDate=formatter.parse(endTime);

}catch(ParseException exp){errorMessage.setText("Not a valied Time");}if(endDate.after(startDate) && (startDate.after(date)||startDate.equals(date) )){

String Q="INSERT INTO `messages` ";Q+="(`message`, `subject`, `areaID`, `sTime`, `eTime`, `mFrom`, `mTo`)VALUES ('";Q+=Tmessage.getText()+"','";Q+=Tsubject.getText()+"','";Q+=comboLocation.getSelectedItem()+"','";Q+=startTime+"','";Q+=endTime+"','";Q+=user+"','";Q+=comboMto.getSelectedItem()+"')";UpdateQuery(Q);out.println("Q"+comboMto.getSelectedItem()); clear();}else {

errorMessage.setText("Message is not stored.. \n Sart time may be after the End time or before the Current time: ");

}}if(command=="Clear"){

clear();}if(command=="Back"){

fram.setVisible(false);fram=null;

}}}

private void UpdateQuery(String Q){ String b="true"; try {

Class.forName("com.mysql.jdbc.Driver").newInstance();String username = "na_e2002";String password = "Eclipse";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();stmt.executeUpdate(Q);stmt.close();}catch( Exception e ) {

System.out.println(e.getMessage());e.printStackTrace();

System.out.println("Exception S O O R Y ");}

}

private void clear(){Tsubject.setText("");Tmessage.setText("");errorMessage.setText("");

________________________________________________________________________159

Page 163: Location and Time Based Information Exchange System

________________________________________________________________________

fillTime();

}private void fillComboBox(){

try {Class.forName("com.mysql.jdbc.Driver").newInstance();String username = "na_e2002";String password = "Eclipse";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();tring Q="SELECT groupID FROM `group`";ResultSet rs = stmt.executeQuery(Q);comboMto.addItem("All");while( rs.next() ){comboMto.addItem(rs.getString("groupID"));}

Q="SELECT userID FROM `users`";rs = stmt.executeQuery(Q);

hile( rs.next() ){comboMto.addItem(rs.getString("userID"));

}Q="SELECT * FROM `location`";rs = stmt.executeQuery(Q);

while( rs.next() ){comboLocation.addItem(rs.getString("areaID")+" "+rs.getString("usage"));}stmt.close();}catch( Exception e ) {

System.out.println(e.getMessage());e.printStackTrace();System.out.println("Exception S O O R Y ");

}}private void fillTime(){

Date dateFill=new Date();for(int i=0;i<24;i++){

sH.addItem(new Integer(i));eH.addItem(new Integer(i));

}

for(int i=0;i<60;i=i+5){sM.addItem(new Integer(i));eM.addItem(new Integer(i));

}sH.setSelectedItem(new Integer(dateFill.getHours()));sM.setSelectedItem(new Integer(5*(dateFill.getMinutes()/5)+5));dateFill.setMinutes(dateFill.getMinutes()+15);eH.setSelectedItem(new Integer(dateFill.getHours()));eM.setSelectedItem(new Integer(5*(dateFill.getMinutes()/5)+5));SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

Date date=new Date();

________________________________________________________________________160

Page 164: Location and Time Based Information Exchange System

________________________________________________________________________

for(int i=0;i<7;i++){ String s=sdf.format(date); sD.addItem(s); eD.addItem(s); date.setDate(date.getDate()+1); } date=new Date(); sD.setSelectedItem(sdf.format(date)); eD.setSelectedItem(sdf.format(date));}

}

________________________________________________________________________161

Page 165: Location and Time Based Information Exchange System

________________________________________________________________________A6.7 showOnMap

package LTBIES.Client;

import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.io.*;import java.net.*;import java.util.*;

import java.text.*;import javax.swing.border.*;

public class showOnMap extends Thread{ String user; String ip; Location loc; int pX=0,pY=0; JFrame frame ; CustomScrollPane sp ; Graphics g;int r=5; String Floor,Room; JLabel label; ImageIcon image; showOnMap(String name,String ip){ this.user=name; this.ip=ip; label=new JLabel(); sp = new CustomScrollPane(label); frame =new JFrame("LTBIES "+user+"'s Location on map"); frame.getContentPane().add(sp); frame.setSize(500,600); frame.setVisible(true); start(); } public void run(){ while(frame.isShowing()){ loc=new Location(ip); loc.getLocation(); if(pX+10>loc.getX()|| pX-10<loc.getX() || pY+6>loc.getY()|| pY+10>loc.getY()){ pX=loc.getX(); pY=loc.getY(); Floor=loc.getFloor(); Room=loc.getRoom(); image=new ImageIcon(Floor+".png"){ public void paintIcon(Component c,Graphics gg,int l,int m){ super.paintIcon(c, gg, 0,0 ); g=gg;

g.setColor(new Color(0,255,0)); g.drawString("Mr. "+user+" is in Area "+Room+" on Floor "+Floor,700,25); g.setColor(new Color(255,0,0)); g.drawString(user,pX/4, pY/4); }

________________________________________________________________________162

Page 166: Location and Time Based Information Exchange System

________________________________________________________________________ }; label.setIcon(image); } try{ sleep(2000); }catch (InterruptedException e) {} }}}class CustomScrollPane extends JPanel{ protected JScrollBar m_vertSB; protected JScrollBar m_horzSB; protected CustomViewport m_viewport; protected JComponent m_comp;

public CustomScrollPane(JComponent comp) { setLayout(null); m_viewport = new CustomViewport(); m_viewport.setLayout(null); add(m_viewport); m_comp = comp; m_viewport.add(m_comp);

m_vertSB = new JScrollBar( JScrollBar.VERTICAL, 0, 0, 0, 0); m_vertSB.setUnitIncrement(5); add(m_vertSB);

m_horzSB = new JScrollBar( JScrollBar.HORIZONTAL, 0, 0, 0, 0); m_horzSB.setUnitIncrement(5); add(m_horzSB);

AdjustmentListener lst = new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { m_viewport.doLayout(); } }; m_vertSB.addAdjustmentListener(lst); m_horzSB.addAdjustmentListener(lst); }

public void doLayout() { Dimension d = getSize(); Dimension d0 = m_comp.getPreferredSize(); Dimension d1 = m_vertSB.getPreferredSize(); Dimension d2 = m_horzSB.getPreferredSize();

int w = Math.max(d.width - d1.width-1, 0); int h = Math.max(d.height - d2.height-1, 0); m_viewport.setBounds(0, 0, w, h); m_vertSB.setBounds(w+1, 0, d1.width, h); m_horzSB.setBounds(0, h+1, w, d2.height);

________________________________________________________________________163

Page 167: Location and Time Based Information Exchange System

________________________________________________________________________

int xs = Math.max(d0.width - w, 0); m_horzSB.setMaximum(xs); m_horzSB.setBlockIncrement(xs/5); m_horzSB.setEnabled(xs > 0);

int ys = Math.max(d0.height - h, 0); m_vertSB.setMaximum(ys); m_vertSB.setBlockIncrement(ys/5); m_vertSB.setEnabled(ys > 0);

m_horzSB.setVisibleAmount(m_horzSB.getBlockIncrement()); m_vertSB.setVisibleAmount(m_vertSB.getBlockIncrement()); }

public Dimension getPreferredSize() { Dimension d0 = m_comp.getPreferredSize(); Dimension d1 = m_vertSB.getPreferredSize(); Dimension d2 = m_horzSB.getPreferredSize(); Dimension d = new Dimension(d0.width+d1.width, d0.height+d2.height); return d; }

class CustomViewport extends JPanel { public void doLayout() { Dimension d0 = m_comp.getPreferredSize(); int x = m_horzSB.getValue(); int y = m_vertSB.getValue(); m_comp.setBounds(-x, -y, d0.width, d0.height); } }}

________________________________________________________________________164

Page 168: Location and Time Based Information Exchange System

________________________________________________________________________A6.8 showOnMapAll

package LTBIES.Client;

import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.io.*;import java.net.*;import java.util.*;

import java.text.*;import javax.swing.border.*;

public class showOnMapAll extends Thread{ String user; String ip; Location loc; int pX=0,pY=0; JFrame frame ; CustomScrollPane sp ; Graphics g;int r=5; String Floor="level4",Room; JLabel label; ImageIcon image; JButton floor1,floor3,floor2,floor4; HashMap userList=new HashMap();

showOnMapAll(HashMap userList){ this.userList=userList; this.user="Shouket"; this.ip="192.168.100.229";ImageIcon floor1Image=new ImageIcon("b_floor1.png"); ImageIcon floor2Image=new ImageIcon("b_floor2.png"); ImageIcon floor3Image=new ImageIcon("b_floor3.png"); ImageIcon floor4Image=new ImageIcon("b_floor4.png"); floor1=new JButton(floor1Image); floor2=new JButton(floor2Image); floor3=new JButton(floor3Image); floor4=new JButton(floor4Image);

floor1.setActionCommand("First Floor"); floor2.setActionCommand("Second Floor"); floor3.setActionCommand("Thired Floor"); floor4.setActionCommand("Fourth Floor"); floor1.setBackground(new Color(253,176,102));// floor2.setBackground(new Color(253,176,102));// floor3.setBackground(new Color(253,176,102));// floor4.setBackground(new Color(253,176,102));// floor1.setActionCommand("one"); floor2.setActionCommand("two"); floor3.setActionCommand("three");

________________________________________________________________________165

Page 169: Location and Time Based Information Exchange System

________________________________________________________________________ floor4.setActionCommand("four"); mapListener listener=new mapListener(); floor1.addActionListener(listener); floor2.addActionListener(listener); floor3.addActionListener(listener); floor4.addActionListener(listener); JPanel panel=new JPanel(); panel.add(floor1); panel.add(floor2); panel.add(floor3); panel.add(floor4); panel.setBackground(new Color(211,106,1));// label=new JLabel(); sp = new CustomScrollPane(label); frame =new JFrame("LTBIES "+user+"'s Location on map"); frame.getContentPane().add("North",panel); frame.getContentPane().add("Center",sp); frame.setSize(500,600); frame.setBackground(new Color(253,176,102));// frame.setVisible(true); start(); } public void run(){ while(frame.isShowing()){ loc=new Location(ip); loc.getLocation(); image=new ImageIcon(Floor+".png"){ public void paintIcon(Component c,Graphics gg,int l,int m){ super.paintIcon(c, gg, 0,0 ); g=gg; Set list=userList.keySet(); Iterator iter=list.iterator(); int draw=12; while(iter.hasNext()){

user=(String)iter.next(); ip=(String)userList.get(user); loc=new Location(ip); loc.getLocation(); pX=loc.getX(); pY=loc.getY(); String level=loc.getFloor(); Room=loc.getRoom(); if(Floor.equals(level)){ g.setColor(new Color(0,255,0)); g.drawString("Mr. "+user+" is in Area "+Room+" on Floor "+Floor,700,draw+12); g.setColor(new Color(255,0,0)); g.drawString(user,pX/4, pY/4+draw); draw+=12; } } } }; label.setIcon(image);

________________________________________________________________________166

Page 170: Location and Time Based Information Exchange System

________________________________________________________________________

try{ sleep(2000); }catch (InterruptedException e) {} } }public static void main(String[] str){ HashMap userList=new HashMap(); userList.put("Nadeem","192.168.100.229"); userList.put("Shouket","192.168.100.147"); userList.put("Bilal","192.168.100.186"); userList.put("Bilal Sarwar","192.168.100.235"); String name="Nadeem"; String ip="192.168.100.229"; showOnMapAll show=new showOnMapAll(userList);}class mapListener implements ActionListener{ public void actionPerformed(ActionEvent e) { String command=e.getActionCommand(); System.out.println(command+user); if(command=="one"){ Floor="level1"; } if(command=="two"){ Floor="level2"; } if(command=="three"){ Floor="level3"; } if(command=="four"){ Floor="level4"; } } }}A6.9 onlineUserspackage LTBIES.Client;

import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.io.*;import java.net.*;import java.util.*;import java.text.*;import javax.swing.border.*;public class onlineUsers extends JPanel{

HashMap userList;JTextArea Tmessage;onlineUsers(HashMap userList){

this.userList=userList;System.out.println(userList);JLabel label=new JLabel("Online Persons");Font font = new Font("Serif",Font.PLAIN,35);label.setFont(font);

________________________________________________________________________167

Page 171: Location and Time Based Information Exchange System

________________________________________________________________________

Tmessage=new JTextArea("",10,50);

Tmessage.setBorder(new TitledBorder( LineBorder.createBlackLineBorder(),"List of Online persons", TitledBorder.LEFT, TitledBorder.TOP, new Font ("Serif", Font.ITALIC, 20), Color.blue));

//JButton show=new JButton("Show on Map");JButton show=new JButton(new ImageIcon("onMap.png"));show.setActionCommand("Show");

onLineUsersListener listener=new onLineUsersListener(); show.addActionListener(listener);

setLayout(new BorderLayout());add(label,BorderLayout.NORTH);add(Tmessage,BorderLayout.CENTER);add(show,BorderLayout.SOUTH);fillCList();

}private void fillCList(){

Set set=userList.keySet();Iterator iter=set.iterator();while(iter.hasNext()){

String s=(String)iter.next();String ip=(String)userList.get(s);System.out.println("ip to get location is "+ip);Location loc=new Location(ip);String room=loc.getRoom();String floor=loc.getFloor();

Tmessage.append("Mr. "+s+" is in Room "+room+" on floor "+floor+"\n");System.out.println(s);

}}

class onLineUsersListener implements ActionListener{public void actionPerformed(ActionEvent e) {

String command=e.getActionCommand();if(command=="Show"){

System.out.println("Show on Map is pressed");showOnMapAll show=new showOnMapAll(userList);

}}

}}

________________________________________________________________________168

Page 172: Location and Time Based Information Exchange System

________________________________________________________________________A6.10 SimulationForm

package LTBIES.Client;

import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import java.util.*;import java.text.*;import javax.swing.border.*;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Driver;import java.sql.Statement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;public class SimulationForm extends JPanel{ JLabel TName;

JButton onMap;static JFrame jf;JComboBox hours,minutes,date,comboLocation;boolean on=false;SimulationForm(String user){

JLabel LTime,Lhour,Lminutes,Ldate; JLabel label,LName,LRoom,TName; JPanel panel1,panel2,panel3,panel5;

setLayout(new GridLayout(5,3));comboLocation=new JComboBox();Font font = new Font("Serif",Font.PLAIN,15);label=new JLabel("Please enter the Area & Time for Simulation ");LName=new JLabel(" Name of Client: ");LRoom=new JLabel(" Area: ");TName=new JLabel(user);onMap=new JButton("Start Simulation");onMapListener listener=new onMapListener();onMap.addActionListener(listener);panel1=new JPanel();panel2=new JPanel();panel3=new JPanel();panel5=new JPanel();hours=new JComboBox();minutes=new JComboBox();date=new JComboBox();LTime=new JLabel("Time: ");Lhour=new JLabel(" Hours ");Lminutes=new JLabel("Minutes ");Ldate=new JLabel("Date ");font = new Font("Serif",Font.PLAIN,20);LTime.setFont(font);LRoom.setFont(font);panel5.add(LTime);panel5.add(Lhour);

________________________________________________________________________169

Page 173: Location and Time Based Information Exchange System

________________________________________________________________________

panel5.add(hours);panel5.add(Lminutes);panel5.add(minutes);panel5.add(Ldate);panel5.add(date);panel1.add(LName);panel1.add(TName);panel1.add(label);panel2.add(LRoom);panel2.add(comboLocation);panel3.add(onMap);add(panel1);add(panel2);add(panel5);add(panel3);fillTime();fillComboBox();jf=new JFrame("Simulation Test");jf.getContentPane().add(this);jf.setSize(440,240);jf.setLocation(600,400);jf.setVisible(true);

}

public static void main(String arg[]){SimulationForm mL=new SimulationForm("nadeemAhmad");

}public String getName(){

if(on)return TName.getText();elsereturn null;

}public String getArea(){

if(on){String s=(String) comboLocation.getSelectedItem();s=s.substring(0,5);return s.trim();

}elsereturn null;

}

public String getTime(){if(on){

String Ctime=(String)date.getSelectedItem();Ctime+=" "+hours.getSelectedItem();Ctime+=":"+minutes.getSelectedItem()+":00";return Ctime;

}elsereturn null;

________________________________________________________________________170

Page 174: Location and Time Based Information Exchange System

________________________________________________________________________

}

public class onMapListener implements ActionListener{public void actionPerformed(ActionEvent e) {

if(on){on=false;onMap.setLabel("Start Simulation");

}else{

on=true;onMap.setLabel("Stop Simulation");

}}

}public void fillTime(){

for(int i=0;i<24;i++){hours.addItem(new Integer(i));

}

for(int i=0;i<60;i=i+5){minutes.addItem(new Integer(i));

}SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

Date date1=new Date(); for(int i=0;i<7;i++){ date1.setMonth(5+i); String s=sdf.format(date1); date.addItem(s); }

}public void fillComboBox(){

try {Class.forName("com.mysql.jdbc.Driver").newInstance();

String username = "na_e2002";String password = "Eclipse";

String url = "jdbc:mysql://mysql.it-c.dk/" + username;Connection con = DriverManager.getConnection(url, username , password);

Statement stmt = con.createStatement();String Q="SELECT * FROM `location`";ResultSet rs = stmt.executeQuery(Q);

while( rs.next() ){comboLocation.addItem(rs.getString("areaID")+" "+rs.getString("usage") );}stmt.close();}catch( Exception e ) {

System.out.println(e.getMessage());}

}

}

________________________________________________________________________171