Embed
Email

thesis

Document Sample

Shared by: huanghengdong
Categories
Tags
Stats
views:
6
posted:
12/16/2011
language:
pages:
106
Mobile Workers Communication

System



By Jeremy Thompson









The School of Information Technology and

Electrical Engineering

The University of Queensland



Submitted for the degree of Bachelor of Engineering (Pass)

in the division of Software Engineering

29 October 2003

The Dean

School of Engineering

University of Queensland

St Lucia, Q 4072





Dear Professor Simmons,





In accordance with the requirements of the degree of Bachelor of Engineering

(Pass) in the division of Software Engineering, I present the following thesis

entitled:





“Mobile Workers Communication System”





This work was performed in partnership with Mr Thomas Daley and under the

supervision of Mr Richard Cocks. I declare that the work submitted in this

thesis is my own, except as acknowledged in the text and footnotes, and has

not been previously submitted for a degree at the University of Queensland or

any other institution.





Yours sincerely,









_______________________________

Jeremy Thompson.

Mobile Worker Communication System









2

Mobile Worker Communication System









Abstract



The Mobile Workers Communication System is intended to assist Mobile

Workers to keep in contact with a centralised Office. The research, design

and development of the Mobile Workers Communication System have been

undertaken in partnership with Mr Thomas Daley under the supervision of Mr

Richard Cocks.





The Mobile Workers Communication System is a two part solution, the PC

based Communications Framework and the Mobile Device Handset. The

Communications Framework is an extendable software framework that

facilitates communication between entities on the system. The Mobile Device

Handset is a specially designed device intended for use by a mobile worker in

an industrial setting.





The Communications Framework software suite has been completed and

provides core programs necessary for the system. It also provides a number

of demonstration Clients that can be used to communicate on the system.

The Communications Framework also provides for easy extension and

development of new Clients so that users can easy adapt the Framework to

meet their particular needs.





The Mobile Device Handset is still at the prototype hardware phase. Although

all of the major components have been designed and implemented the device

is unable to connect to the Communications Framework via GPRS/IP. This is

due to failure within the embedded software.





In summary the Mobile Workers Communication System is almost fully

complete. If the Mobile Device Handset was able to connect then the system

would be fully functional.









3

Mobile Worker Communication System









4

Mobile Worker Communication System









Table of Content

Abstract ..........................................................................................................................3

Table of Content ............................................................................................................5

List of Figures ................................................................................................................9

List of Tables ...............................................................................................................11

1: Problem Overview ...................................................................................................13

1.1: Problem Area ....................................................................................................13

1.2: The Mobile Workers Communication System .................................................14

1.2.1: Mobile Device Handset .............................................................................15

1.2.2: Communication Framework ......................................................................15

1.3: Division of Contributions .................................................................................16

1.4: Outline of Chapters...........................................................................................16

2: Background Information..........................................................................................19

2.1: Mobile telecommunications..............................................................................19

2.1.1: Mobile telecommunications - General.......................................................19

2.1.1.1: Mobile technology generations...........................................................19

2.2.1.1.1: Pre 1G Networks..........................................................................20

2.1.1.1.2: 1G Networks ................................................................................21

2.1.1.1.3: 2G Networks ................................................................................21

2.1.1.1.4: 2.5G Networks .............................................................................22

2.1.1.1.5: 3G Networks ................................................................................22

2.1.1.1.6: 4G Networks ................................................................................22

2.1.2: Mobile telecommunications - Specific ......................................................23

2.1.2.1: GSM Mobile Networks.......................................................................23

2.1.2.2: Cellular Mobile Networks ..................................................................23

2.1.2.3: GSM....................................................................................................24

2.1.2.4: GPRS ..................................................................................................25

2.2: Solution Justification ........................................................................................26

2.2.1: Cost ............................................................................................................26

2.2.2: Time Efficiency .........................................................................................27

3: Solution Specification..............................................................................................29

3.1: Core Functionality ............................................................................................29

3.1.1: Message passing ........................................................................................29

3.1.2: Office Environment Client.........................................................................30

3.1.3: Concise Information Passing .....................................................................30

3.2: Extended Functionality .....................................................................................30

3.2.1: Interaction with multiple entities under different interfaces......................30

3.2.2: Extendibility...............................................................................................31

3.2.3: Responsive .................................................................................................31

4: Hardware Implementation .......................................................................................33

5: Software Implementation.........................................................................................35

5.1: Design Goals.....................................................................................................35

5.1.1: Message passing ........................................................................................35

5.1.2: Office Environment Client.........................................................................35

5.1.3: Concise Information ..................................................................................36

5.1.4: Interaction on different interfaces..............................................................36

5.1.5: Extendibility...............................................................................................36





5

Mobile Worker Communication System





5.1.5.1: Simplified modular structure ..............................................................36

5.1.5.2: Easy to adapt and extend ....................................................................36

5.1.6: Responsive .................................................................................................36

5.2: Design decisions and reasoning........................................................................36

5.2.1: Framework language..................................................................................36

5.2.2: Framework Protocol ..................................................................................37

5.3: Framework Implementation..............................................................................38

5.3.1: Framework Component Overview.............................................................39

5.3.1.1: Server ..................................................................................................39

5.3.1.2: Module ................................................................................................40

5.3.1.3: Client...................................................................................................40

5.3.2: Class Descriptions......................................................................................40

5.4: Framework Operation .......................................................................................41

5.4.1: Client connections......................................................................................42

5.4.2: Message passing ........................................................................................42

5.5: Extending the Framework.................................................................................43

5.5.1: Creating new Clients..................................................................................43

5.5.2: Creating new Modules ...............................................................................43

5.5.3: Extension Example ....................................................................................44

5.5.3.1: Client Extension - SensorClient..........................................................44

5.5.3.2: Module Extension – LoggingUDPModule .........................................46

6: Evaluation ................................................................................................................47

6.1: Product Evaluation............................................................................................47

6.1.1: Core Functionality .....................................................................................48

6.1.1.1: Message Passing .................................................................................48

6.1.1.2: Office Environment Client..................................................................48

6.1.1.3: Concise Information ...........................................................................48

6.1.2: Extended Functionality ..............................................................................48

6.1.2.1: Interaction with entities on different interfaces ..................................48

6.1.2.2: Extendibility........................................................................................49

6.1.2.3: Responsive ..........................................................................................49

6.1.3: Summary....................................................................................................49

7: Future Development ................................................................................................51

7.1: Security Features...............................................................................................51

7.2: Backend Database.............................................................................................51

7.3: Framework Control Client ................................................................................51

8: Conclusion ...............................................................................................................53

Appendix A Code Listings...........................................................................................55

Code Listing 1 - Module ..........................................................................................56

Code Listing 2 – AbstractModule............................................................................58

Code Listing 3 – ConnectDialog..............................................................................60

Code List 4 – DeviceException ...............................................................................63

Code Listing 5 – ModuleFactory .............................................................................64

Code Listing 6 – TCPReceiver ................................................................................67

Code Listing 7 – SensorClient .................................................................................68

Code Listing 8 – Server ...........................................................................................73

Code Listing 9 – TCPModule ..................................................................................81

Code Listing 10 – TCPReceiver ..............................................................................83

Code Listing 11 – UDPModule ...............................................................................85

Code Listing 12 – UDPReceiveThread....................................................................87





6

Mobile Worker Communication System





Code Listing 13 – WiredClient ................................................................................89

Appendix B – Companion Disk.................................................................................101

Bibliography ..............................................................................................................103









7

Mobile Worker Communication System









8

Mobile Worker Communication System







List of Figures

Figure 1 - Usage........................................................................................................14

Figure 2 - Solution Overview ...................................................................................15

Figure 3 - Message Passing....................................................................................30

Figure 4 - Embedded Sensor ..................................................................................31

Figure 5 - Framework Overview..............................................................................39

Figure 6 - Client Connection....................................................................................42

Figure 7 - Message Passing....................................................................................43

Figure 8 - Inheritance Diagram ...............................................................................44









9

Mobile Worker Communication System









10

Mobile Worker Communication System







List of Tables

Table 1 - Chapter Summary ....................................................................................16

Table 2 - Wireless Network Generations...............................................................20

Table 3 - 3G Transfer Speeds.................................................................................22

Table 4 - GSM cellular System Breakdown ..........................................................25

Table 5 - Functional Specification ..........................................................................29

Table 6 - Functional Specification ..........................................................................35

Table 7 - Communication Framework Protocol ....................................................38

Table 8 - Class Descriptions ...................................................................................41

Table 9 - Functionality Evaluation ..........................................................................47









11

Mobile Worker Communication System









12

Mobile Worker Communication System







1: Problem Overview

Wireless communications have always been a rapidly developing technology

area. This technology development has seen the increase in new services

which provide the tools to create solutions to new and existing problem areas.

The product proposed by this thesis is aimed at solving a particular

communications problem and is aiming to provide users a flexible, simple to

use, extendable and powerful means of communication.





“Effective and efficient communication between mobile workers and

centralised communications base.”







1.1: Problem Area

The problem being addressed by this thesis is designing a cost

effective, flexible and durable solution for communication between mobile

entities and non-mobile entities in an industrial setting. An example of this

type of system would be a large organization that has a number of mobile

workers. Such a scenario can be seen in figure 1. The problem faced is how

to keep in contact with each mobile worker in a cost effective, efficient and

simple manner whilst the worker is at a remote job site. A key factor in this

problem area is the environment that the mobile worker is operating in.

Typically this will be in an industrial environment, for example on a building

site. A fundamental problem faced by any solution will be durability and

robustness.









13

Mobile Worker Communication System









Figure 1 - Usage









1.2: The Mobile Workers Communication

System

The solution proposed is a two part solution. Firstly a purpose built mobile

handset has been designed which is used by the mobile worker at remote





14

Mobile Worker Communication System





locations. Secondly there is an integrated communication framework

designed to control and manage communication. An overview of the solution

can be seen in the figure below.









Figure 2 - Solution Overview







1.2.1: Mobile Device Handset

Details of the Mobile Device handset can be found in Mr Thomas Daley’s

Thesis.







1.2.2: Communication Framework

The second part of the solution is the Communications Framework which is a

generalised Server Client communications package. As the Mobile Device









15

Mobile Worker Communication System





Handset is designed to implement GPRS wireless communications1, the

Framework provides communication via standard IP channels, specifically

through TCP and UDP (datagram) channels. The Framework designed uses

Java to implement the core functionality whilst providing extended

functionality. Please refer to the solution specification section for more

details.







1.3: Division of Contributions

This product has been broken down into two sections. The PC based

Communications Framework and the Mobile Device Handset. My main

contribution to the product has been focused on the Communications

Framework however I have also assisted with the embedded software of the

Mobile Device Handset. Details of the Mobile Device Handset can be seen in

Mr Thomas Daley’s Thesis.









1.4: Outline of Chapters

Below is a generalised description of the following chapters and gives a very

brief overview of the contents of each section.

Table 1 - Chapter Summary

Chapter Heading Description

2 Background Information Gives background information

concerning the solution

3 Solution Specification Gives a detailed functional

specification for the solution

4 Hardware Implementation Please refer to Thomas Daley’s

Thesis for more information on the

hardware implementation

5 Software Implementation This chapter gives details

concerning the Communication

Framework software.





1

Please refer to the background information section for more information on GPRS





16

Mobile Worker Communication System





6 Evaluation This chapter gives an evaluation of

the product and how well each

functional specification was

achieved (or not achieved).

7 Future Development This section outlines the possible

future development avenues for this

product

8 Conclusion The summary of this document









17

Mobile Worker Communication System









18

Mobile Worker Communication System









2: Background Information

2.1: Mobile telecommunications

2.1.1: Mobile telecommunications - General

The wireless telecommunications industry has seen phenomenal

growth. According to Nokia, there will be more than one billion wireless

subscribers by the year 2005. The wireless market is enormous: it can afford

and will demand optimised solutions [25]. Globally mobile services were

worth 380 billion Euros in 2002 however that figure pales in comparison to the

prediction that mobile services will be worth 625 billion Euros by 2007.

Currently voice communication provided approximately 90 percent of the

income however this figure is predicted to fall to 69 percent by 2007. This can

be directly correlated to the expansion of high speed data transfer services

provided by the new 3G networks.





With the expansion of the user base for wireless communication there has

also been a corresponding increase in mobile communications technology.

This new technology enables a much wider range of communication solutions

and services to be offered to consumers.





As wireless telecommunications technology advances so too do the forms

and type of wireless networks deployed by Mobile communications service

providers. Following is a general discussion of the evolution of wireless

communications technology and the networks provided by each evolution.







2.1.1.1: Mobile technology generations



Mobile communications networks have seen a number of generational

evolutions. Typically a network is described by which technology generation it

is part of. The table below lists the wireless communication generations and

some example associated with network types.







19

Mobile Worker Communication System







Network Generation Service

pre 1G networks Experimental systems

1G networks NMT

C-Nets

AMPS

TACS

2G networks GSM

Cdma 1

DAMPS

Tdma

PDC

2.5G networks GPRS

cdma2000 1x

3G networks UMTS FDD and TDD

cdma2000 1x EVDO

cdma2000 3x

TD-SCDMA

Arib WCDMA

EDGE2

IMT-2000 DECT

4G networks Still in research stages

Table 2 - Wireless Network Generations







2.2.1.1.1: Pre 1G Networks

This wireless telecom generation can be seen as the origins of the whole

industry. The culmination of the generation was the type of service provided

by Bell laboratories in 1976 in the New York City area. Bell Mobile Phones

provided a “mobile” service that supported 543 customers on 12 channels.

However the waiting list for the service was around 3700 people with the

service being severely limited by excessive blocking (blocking occurred when



2

EDGE (Enhanced Data rate for GSM Evolution) can in fact be seen as a 2.75G technology or an

interim step from 2/2.5G to 3G networks.





20

Mobile Worker Communication System





there were no resources available to service the customer). The service was

provided by a single high powered base station.







2.1.1.1.2: 1G Networks

In the 1980’s 1G networks began appearing which utilised the idea of cells

(which can be seen in today’s networks). The premise of cellular networks is

that instead of using a single high powered base station transmitter which

services the whole network, a number of smaller lower powered transmitters

are used. Each of the smaller transmitters service a smaller localised area (or

cell) which, when combined with other cells, provide the full network

coverage. 1G cellular networks were analogue and did not efficiently use the

available bandwidth i.e. the amount of data that 1G networks could transmit

per time cycle (usually given as bits per second) was extremely low and

hence a 1G networks spectral efficiency was also very low.







2.1.1.1.3: 2G Networks

With the advent of 2G networks mobile telecommunications became digital.

The human voice was now sampled and transmitted digitally (i.e. as binary

highs and lows) as apposed to the 1G network where the human view was

transmitted as a full analogue wave. This digitalisation provided the means to

dramatically increase the spectral efficiency of the network. Maximum3 data

rates of 2G networks are in the range of 9.6 kb/s to 14.4 kb/s. The

digitalisation of information in 2G networks had a number of effects on the

service provided. The major effect was that digital data could now also be

transmitted (as apposed to the digital transmission of the voice). This data

transfer enabled new facilities on the network like caller ID and SMS text

messaging. However digitalisation also had a negative effect on the quality of

the voice transmission simply due to loss of information during the sampling

process4. 2G networks are very widely implemented and used across the

globe.



3

Subject to a number of factors eg signal strength. The maximum rates are given for optimal

conditions.

4

Amongst other factors





21

Mobile Worker Communication System





2.1.1.1.4: 2.5G Networks

2.5G technologies are not seen as a full generational change due to them

generally being an extension of existing 2G network technologies. For

example, GPRS is a packet layer protocol which can be built upon GSM

networks to provide a packet switching facility which allows for data transfer

rates of up to 115 kb/s. 2.5G offers enhanced data rates to 2G networks and

are primarily targeted at data transfer operations5. GPRS will be discussed in

detail later in this document.







2.1.1.1.5: 3G Networks

Third generation networks are characterised by high data transfer rates and

high bandwidth. Approximate maximum data transfers are given in





Type of device Maximum transfer rate

Stationary device 2.05 Mb/s

Slow moving device 384 kb/s

Fast moving device 128 kb/s

Table 3 - 3G Transfer Speeds



There are a wide range of network technologies available in the 3G band and

not all are tradition telecommunications network communications. For

example wireless LAN and Bluetooth. Both of these technologies are wired

networks based but are beginning to be accepted into wireless

telecommunications applications. There is still much debate about 3G

network development and deployment, however Australia does have some

3G networks deployed. Specifically they are the Hutchison’s “3” network and

Telstra's Mobile Loop service6. Both of these services are targeted at

wireless multimedia applications which require high data transfer rates.







2.1.1.1.6: 4G Networks





5

Like mobile internet access

6

The Telstra Mobile loop service is not strictly a 3G network but is close.





22

Mobile Worker Communication System





Fourth generation networks are still only in the research stages. For example,

a recent Japanese effort to design a 4G network that would offer transfer

speeds of around 100Mb/s. The scale of a cell in this network is

approximately the size of a single street. 4G technology may see the total

integration of the wireless telecommunications and wired network technology.







2.1.2: Mobile telecommunications - Specific

2.1.2.1: GSM Mobile Networks

The GSM mobile network is the type of wireless network most commonly

deployed within Australia and as such provides the basic technology utilised

by the solution to provide its functionality. Following is a discussion on the

general form of cellular networks7. The GSM mobile network will then be

discussed in more detail.







2.1.2.2: Cellular Mobile Networks



There are five basic components in a cellular system:

• Radios

• Switching systems

• Databases

• Processing centres

• External networks

Outlined in Appendix B is a general schema for a Cellular system. Although

components are represented separately on the diagram, many components

will in fact be combined. For example, Base transceiver station (BTS) and

Base Station centres (BSC) will often be combined in a single base station.





A Mobile cellular network uses a modular system design. This means that the

overall system is broken down into a number of smaller sub systems that

each gives coverage to an area of the overall system coverage. This is done

for a number of reasons, firstly the power required to transmit a radio signal is



7

GSM is a cellular network





23

Mobile Worker Communication System





proportional to the radius of the signal. This means that it is more economical

to use a number of low power transmitters then to use a signal high power

transmitter. Another reason for the cellular system is that there are a limited

number of frequencies open to use, which limits the number of active users of

a system. To work around this problem a frequency can be reused if there is

sufficient distance between transmitters using that frequency. Original

designs, which used a single high-powered base tower, only allowed for 6

channels and had a twenty percent blocking rate (blocking occurs when there

is no free resources for new usage).







2.1.2.3: GSM

GSM has become a standard within the Australian mobile networks

and to a large extent, worldwide. Group Speciale Mobile or Global System for

Mobile communication was first developed in Europe with ETSI standards

backing and has since spread across the world. GSM systems have a

number of advantages over other systems. The Subscriber Identifier Module

(SIM) card is a vital component of the GSM Network. The SIM card holds

subscriber information and allows for subscriber identification. The SIM card

is simply inserted in a Mobile Handset and identifies the user when the

handset connects to the network. Due to this separation of subscriber

identification and mobile handset GSM networks allow for simple Global

Roaming. This allows users to move between different networks (outside of

their primary network) using the one GSM SIM card.





GSM is a digital cellular system, which uses digital signal transmission where

the human voice is modelled by high speed Digital Signal Processors (DSP)

using a form of the Regular Pulse Excitation/Long Term Prediction (RPE-LTP)

algorithm. The human voice is sampled at 8 kHz and then quantised to 13

bits/Kbps. The digital signal is then compressed (approximately 4.78 to 1)

before being transmitted [25].





Digital GSM system standards are defined by the frequency that it occupies.

Those being:





24

Mobile Worker Communication System





• 900 MHz (GSM-900)

• 1800 MHz (GSM-1800)

• 1900 MHz (GSM-1900)

Below is a summary of the GSM cellular System.

Band GSM-900 GSM-1800 GSM-1900

Uplink (MHz) 935-960 1805-1880 1930-1990

Downlink (MHz) 890-915 1710-1785 1850-1910

Channel spacing 200 200 200

(kHz)

Minimum number 125 125 125

of channels

Users per 8 8 8

channel

Duplex mode Frequency FDD Frequency

division duplexing division duplexing

(FDD)

Modulation Gaussian GMSK GMSK

minimum shift

keying

Table 4 - GSM cellular System Breakdown



2.1.2.4: GPRS

The General Packet Radio Service is a packet-based system that is

layered over the general GSM network service. It is a second/third generation

(2.5G) service, which provides an end-to-end packet switching service. A

major feature of GPRS is that it only utilises the network when sending or

receiving data, making for efficient usage of the network. Due to this fact

users can have an “always on” connection and only be charged for the data

that they transmit or receive. GPRS will be the starting point for a completely

new range of services and new charging mechanisms (Lewis p51).





Below is a list of the feature of GPRS:

• Reuse of the existing GSM network

• Extension of the GSM for packet switching end to end





25

Mobile Worker Communication System





• Existing circuit-switched services interwork with GPRS

• Efficient resource utilization

• Variable data throughput

• Volume and resource usage based charging schemes

• Close interworking with data communication world especially IP based

systems





The GPRS system has a theoretical throughput of ~115 Kbps although this

largely depends on the underlying GSM network. GPRS systems support

channel aggregation where up to four downlink channels and a single uplink

channel (4+1) are used at the same time (this depends on the GSM/GPRS

module used). There are also a number of different coding schemes which

are used depend on the quality of the transmission channel. For an

unreliable/noisy channel coding scheme, 1 would be used offering better

reliability but only at 9.6 Kbps data transfer rate. Coding scheme 4 offers the

full 115 Kbps transmission speed but without the reliability of coding scheme 1

and hence would only be used on a high quality channel.







2.2: Solution Justification



The central premise of this product is to produce an efficient and effective

communication system for mobile worker. This efficiency and effectiveness

should be seen in both the cost eg monetary and the time taken to

communicate.







2.2.1: Cost

The principle method of cost saving implemented in the solution is fully

utilising the GPRS data communication as the primary means of

communication. GPRS is a packet-based system where the user is only

charged for the actual amount of information transmitted or received. For

example comparing GPRS to SMS each 25c SMS message can contain 160

characters, which using ANSI encoding will occupy 160 bytes of data or 0.16





26

Mobile Worker Communication System





KB. GPRS is charge (using Telstra) at 2.2c per KB therefore for the same

cost of a SMS GPRS can send ~11363 characters. Another factor to note is

the each SMS message is charged at 25c each regardless if the message

contains the full 160 characters eg a 20-character message costs the same

as a 160-character message. GPRS on the other hand is charged on a data

usage volume and hence you are only charged for the number of characters

in the message. It is obvious that using GPRS for the transmission of text

data is preferable to using SMS text messages.







2.2.2: Time Efficiency

Coupled with efficient system interface design (for example token passing for

common messages) the amount of network traffic can be significantly reduced

resulting in cost savings. This has a two-fold impact on the product, not only

does it simplify the users interaction with the product, it also significantly

reduces the possible amount of network traffic. Consider an example of

RACQ road side assistance where dispatch needs to send a message to

repair van 1. The message is “Next Job is at 21 Whitehall St Toowong”. The

mobile mechanic reply would usually be one of the following; “ok”, “will be late

x mins”, “can’t make it”. By having these common replies already agreed

upon by both the dispatch centre and the mobile unit the message passing

can be reduced to token passing eg the message would become the token for

“Next Job is at” plus “21 Whitehall St Toowong” and the replay could simply

be a single letter for the option selected.









27

Mobile Worker Communication System









28

Mobile Worker Communication System









3: Solution Specification



The goal of this product is to pass information by transferring it from one

remote location to another. It needs to take into account a number of key

factors concerning the type of information and the situations surrounding the

two communication end points. It must also conform to a number of core

functionality specifications.









Functionality type Functionality

Core Functionality

Message passing between entities

Provide a client for the Office

environment

Information must be kept as concise as

possible

Extended Functionality

Interact with a number of different

entities which may be using different

communication interfaces

Extendibility

Responsive

Table 5 - Functional Specification



3.1: Core Functionality

3.1.1: Message passing

The whole premise of this solution is communicating information

between entities. The simplest example of this communication is given by the

scenario of a remote worker using the Mobile Device Handset to transmit a

simple text message to the user in the office using a wired client and the office

worker then replying.









29

Mobile Worker Communication System









Figure 3 - Message Passing



This functionality must be seen as a two part operation. Firstly the Mobile

Device Handset must be able to transmit/receive messages in a standardised

form. Secondly the Communications Framework must be able to

receive/transmit messages in a standardised form.







3.1.2: Office Environment Client

The solution must provide a communications endpoint for the Office

Environment. This can be seen as being analogous to providing the Mobile

Device Handset for the Office environment. This client should take into

consideration the different circumstances in which it operates.







3.1.3: Concise Information Passing

The Mobile Device Handset is a communications endpoint that implements a

GPRS wireless connection. This type of connection charges the user for the

data they transmit and receive. Obviously keeping the information that will be

transmitted across such a connection as concise as possible is a key

requirement, as transmitting unnecessary data will only cost the user more

money than needed.







3.2: Extended Functionality

3.2.1: Interaction with multiple entities under different

interfaces

Although the basic specification only requires communication between the

Communication Framework and the Mobile Device Handset, extending this





30

Mobile Worker Communication System





specification so that the Framework can communicate with any entity that is

capable of connected to it would be a great advantage. This extended

specification can be seen formally as the ability of the Framework to facilitate

communication between any entities that can connect via standard IP

channels using the correct protocol syntax.







3.2.2: Extendibility

This specification can be regarded as a partial extension of the previous

specification8. Although the product is engineered towards solving a

particular communications problem, extended functionality can be provided if

the solution provided the ability for the solution to be extended to meet other

communications needs in the same general problem area. An example of this

can be seen as an embedded sensor within a drink vending machine that

transmits a message when products need to be refilled or become out of date.

This can be seen in the following diagram.









Figure 4 - Embedded Sensor







3.2.3: Responsive

Any solution must be responsive to user input and actions. A communication

package would be useless if it takes an excessive time to transmit

information. This is because it is foreseen that some information transmitted



8

Interaction with multiple entities under different interfaces





31

Mobile Worker Communication System





by the solution may have a short life span eg an administration officer sending

the message “can you be there in 5 minutes?” to a mobile worker. If the

system took more then a few minutes to transmit then the message would

essentially become redundant.









32

Mobile Worker Communication System









4: Hardware Implementation

This Thesis was conducted as part of a team of two, myself and Mr Thomas

Daley. For information regarding the Hardware Implementation of the solution

and the embedded software please refer to Thomas’s Thesis.









33

Mobile Worker Communication System









34

Mobile Worker Communication System









5: Software Implementation

5.1: Design Goals

There were a number of design goals used during the design and

development of the Communication Framework when the functional

specifications were taken into account.

Functionality type Functionality

Core Functionality

Message passing between

entities

Provide a client for the Office

environment

Information must be kept as

concise as possible

Extended Functionality

Interact with a number of

different entities which may

be using different

communication interfaces

Extendibility

Responsive

Table 6 - Functional Specification



5.1.1: Message passing

The system must be able to provide the core functionality as set out by

the specifications as determined by the problem area. This was the ability to

pass messages between entities connected to the system in an efficient and

effective manner.







5.1.2: Office Environment Client

The framework provides a concrete implementation of a standard GUI

Client that can communicate with the Communications Framework.







35

Mobile Worker Communication System









5.1.3: Concise Information

The software implementation uses a very simple character based

protocol that minimises the information transferred.







5.1.4: Interaction on different interfaces

The framework can communicate with any entity connected via the

standard IP networking (eg using both UDP and TCP networking).







5.1.5: Extendibility

5.1.5.1: Simplified modular structure

The framework has been designed using modular components in the

method of OO programming.



5.1.5.2: Easy to adapt and extend

The framework gives the eventual user the ability to extend the

framework to meet their specific communications needs. This is done by

providing a combination of abstract interfaces as well concrete

implementation classes.





5.1.6: Responsive

The responsiveness of the implementation is only limited by the

underlying network responsiveness and is thus as responsive as possible.







5.2: Design decisions and reasoning





5.2.1: Framework language

The communications framework has been designed and written in the Java

programming language (Standard Edition version 1.4.1_01). There were a

number of reasons for this;









36

Mobile Worker Communication System





♦ The Java programs are compatible on a large range of operating

systems and hardware configurations. This is one of the major design

characteristic of the language with the Sun using the slogan “Write one,

run anywhere”.

♦ Java offers a number of facilities to implement extendable frameworks.

Specifically Java provides polymorphism and inheritance through the

use of interfaces and abstract classes.

♦ The Java Standard Edition has an extensive standard class library

which is widely used and proven.

♦ Java uses a JIT (Just in Time) complier to maximise operation

execution speed.







5.2.2: Framework Protocol

The protocol used by the framework is a very simple ASCII character based

system implemented on IP networking. The decision to limit the protocol to a

character based stream on IP was made so the framework can be integrated9

with any other system utilising IP networking. The Mobile Device Handset is a

good example of this type of integration. The handset communicates via

GPRS over the IP network. To the communication framework the mobile

handset is simply another connection via IP.





The protocol is outlined in the following table.

ID Syntax Description

Client Requests

100 REGI “name” Registers a device using the

“module” supplied module.

110 DREG Deregisters a device.

120 LOOK_I “device id” Looks up a device based on

a device id.

130 LOOK_N “device Looks up a device based on

name” a device name.





9

Although they must use the correct command syntax





37

Mobile Worker Communication System





140 LOOK_A Looks up all devices.

150 SEND “device id” Sends the message text to

“message text” the device.

160 QUIET Toggles the quiet status of

the client i.e. if quiet the

client will not receive update

lists.

Server Reponses

200 FAIL “failure text” Returned by the server

when an operation fails.

210 OK Operation was successful

220 DATA “device id” Server returns a list of

“device name” device data in the format of

“connected time” DATA device1_data ;

“last message time”; device2_data;



230 UPDATE DATA Server supplies a list of

“device id” “device device information that the

name” “connected client should update.

time” “last message

time”; …

240 REC “device id” Server supplies a message

“message text” sent from the device with the

specified id.

Table 7 - Communication Framework Protocol



5.3: Framework Implementation

The major design decision made concerning the framework implementation

was to create a combination of concrete, abstract and interface classes to

allow for the extendibility of the framework. The exact details of this are

discussed in detail later.









38

Mobile Worker Communication System





5.3.1: Framework Component Overview



The following diagram is a generalised overview of the Communications

Framework. It indicates the basic components and class interactions on a

high level.









Figure 5 - Framework Overview









5.3.1.1: Server

The Server class is the main communication class of the Framework. It

operates as a central controlling mechanism that accepts client connections

and processes them appropriately. The server also retains client information

and controls the passing of messages between clients. The Server is









39

Mobile Worker Communication System





abstracted from the particular mechanisms of the actual communications for a

client. This is handled by the specified intermediary Module object.







5.3.1.2: Module

A Module can be considered as an intermediary entity that sits between the

server and the client. The Server does not deal with the client

communications directly - it relies on a Module object to do this. For example,

the WiredClient client uses a TCPModule as its intermediary to communicate

with the Server and subsequently other clients/devices. In the case of the

TCPModule, if the Server needs to transmit information to the client

connected via that module, it simply calls the send method of the module.







5.3.1.3: Client

A Client can be seen as any entity connected to the Communication

Framework that is using the appropriate communication syntax. A number of

concrete clients are provided with the Framework eg WiredClient,

SensorClient, but a client can effectively be any entity that produces and/or

consumes information and can connect to the Server.







5.3.2: Class Descriptions

Below is a table outlining the core classes provided by the Communication

Framework.





Class Name Class Type Class Description

Server

Server Class The implemented server class

which handles client/module

connections and message passing

Clients

WiredClient Class A TCP based GUI Client designed

to be used on a network.









40

Mobile Worker Communication System





SensorClient Class An example UDP based Client for

an embedded application

Modules

Module Interface Defines the basic structure of all

modules. All modules must either

implement this interface or extend

AbstractModule.

AbstractModule Abstract Defines basic module functionality

as provided by the Module interface

TCPModule Class A TCP based Module. This module

handles a TCP based client.

UDPModule Class A UDP based Module. This module

handles a UDP based client.

LoggingUDPModule Class An example extension module

based on UDPModule that logs

outgoing information into a file.

Utility

ModuleFactory Class The ModuleFactory class provides

static methods to create modules.

Currently only UDPModules and

TCPModules are supported.

Table 8 - Class Descriptions



5.4: Framework Operation



The Server class in the central processing unit of the Communications

Framework. It acts like most standard servers in that it waits for client

connection and then processes client requests. The Server stores selected

information about clients in a database that is continually queried and updated

during operations. There are two main phases of operation for the Server.









41

Mobile Worker Communication System





5.4.1: Client connections

After initialisation, the Server waits for client connections on both TCP and

UDP sockets. The initial connection packet, provided by the client, contains

the information used by the Server to create the appropriate handling Module.

The Server then uses a static method in the ModuleFactory class, to create

the desired handling Module to be used by the Client. Communication is then

routed via the newly created handling Module. This process can be seen in

the following diagram.









Figure 6 - Client Connection







5.4.2: Message passing

As the Server is abstracted from the underlying details of passing a message

(both in receiving the send message request and the transmission of the

actual message) transmitting messages is a very simple process. When the

Server receives a send message request from a Client (via its Module) the

Server identifies the message recipient and retrieves that Client’s Module and

then simply sends the formatted message to the handling module. This can

be seen in the following diagram.









42

Mobile Worker Communication System









Figure 7 - Message Passing









5.5: Extending the Framework

Extending the Communication Framework to meet other communications

needs is a two part process. Firstly implement the new Client using TCP or

UDP and then implement a Module to handle the new type of Client.







5.5.1: Creating new Clients

The design of new Clients to communicate on the Communications

Framework is only limited by two factors. It must communicate via TCP or

UDP and it must communicate using characters in the Communications

Framework’s protocol. Please see the SensorClient example given below for

more details.







5.5.2: Creating new Modules

Modules are created dynamically by the Server to handle Client connections.

To create a new type of Module the following rules must be adhered to.

1. Extend TCPModule or UDPModule to implement the new functionality.

2. Make sure that the new module provides the same constructor

arguments as the underlying TCPModule or UDPModule.





43

Mobile Worker Communication System





3. Implement the methods within the new Module as appropriate for the

new Client.

Below is an inheritance diagram for the Modules contained within the

Communication Framework.









Figure 8 - Inheritance Diagram



Please refer to the LoggingUDPModule for more information on creating new

modules.







5.5.3: Extension Example

5.5.3.1: Client Extension - SensorClient

SensorClient is a very simple GUI client designed to mimic an embedded

sensor within a drink vending machine. The sensor transmits messages

about the level of drinks, status of the machine and drinks sales to another

client connected to the Communication Framework called

“merchandise_manager”. This is done using UDP datagrams where all





44

Mobile Worker Communication System





commands are packaged into datagrams and then sent to the Servers

datagram port.





The sensor client uses five protocol commands REGI, LOOK_N, SEND,

QUIET and DREG. The REGI command is:

"REGI cokemachine101 LoggingUDPModule”

This line tells the Server to create a new Module of type LoggingUDPModule

and to set the name of this client to cokemachine101.

The LOOK_N command is:

"LOOK_N merchandise_manager"

This command requests details about the client called

“merchandise_manager” and is used to get the Identifier of that client so

messages can be sent to it. Data from this request will be return in the form

of a DATA response from the server.

The SEND command is:

"SEND "+manager_id+" "+out

Where the manager_id is replaced by the identifier returned by the LOOK_N

command and the out is replaced by the data to be sent to the

merchandise_manager.

The QUIET command is:

“QUIET”

This command toggles the quiet status of the client. When quiet is true the

server will not send the client the UPDATE responses. It is designed to limit

network communications.

The DREG command is:

“DREG”

This command simply deregisters the device on the Server.





This example shows how easy it is to create a client that can communicate on

the Communication Framework. Please refer to the full code listing in the

appendices for full details.









45

Mobile Worker Communication System





5.5.3.2: Module Extension – LoggingUDPModule

LoggingUDPModule is a very simple extension of the basic UDPModule and

its purpose is to log all outgoing message sent through the module in a file

called “log.log”. To do this LoggingUDPModule extends UDPModule and then

overrides the send method to write the log before using the underlying

UDPModule send method10 to actually transmit the message. Note that

LoggingUDPModule still uses the same constructor arguments as

UDPModule so that the ModuleFactory class can correctly initialise it. The

LoggingUDPModule constructor code is then entered after the call to the

super class’ constructor.









10

Line 65





46

Mobile Worker Communication System









6: Evaluation

6.1: Product Evaluation



When evaluating the product in terms of how successfully it meets the

functional characteristics as determined in the product specification, it must be

noted that most of the functionality can only be tested in terms of successful

operation or “it is working or it is not working”.





The solution functional characteristics are given below as described in the

product specification. The product results are also given.

Functionality type Functionality Product Result

Core Functionality

Message passing between Functionality was not

entities completely satisfied.

Provide a client for the This functionality was

Office environment satisfied

Information must be kept as This functionality was

concise as possible satisfied.

Extended Functionality

Interact with a number of This functionality was

different entities which may satisfied

be using different

communication interfaces

Extendibility This functionality was

satisfied

Responsive This functionality was

satisfied

Table 9 - Functionality Evaluation









47

Mobile Worker Communication System





6.1.1: Core Functionality

6.1.1.1: Message Passing

The Communication Framework allows any entity that successfully connects

to it to be able to pass a message to any other entity that is connected. This

does satisfy this functionality in a general sense. However as the Mobile

Device Handset can not successfully establish a GPRS/IP/UDP connection,

messages passing between connected clients and the Mobile Device Handset

is not possible. Hence this core functionality is not fully satisfied.







6.1.1.2: Office Environment Client

The WiredClient program is provided with the Communications Framework

which provides an interface that can be used in the Office Environment.

Although it is not an overly complex client it does fully satisfy the functionality

of providing an interface for message passing within the Office Environment.







6.1.1.3: Concise Information

The Communication Framework provides a very simplistic character protocol

that keeps the information being passed as concise as possible. Clients can

also nominate if they wish to operate in quit mode meaning that they don’t

receive any unnecessary information. This functionality has been satisfied.







6.1.2: Extended Functionality

6.1.2.1: Interaction with entities on different interfaces

By default the Framework allow for communication with any client using TCP

or UDP which should cover most applications. The Framework is also

designed to allow the extension to other interfaces. This functionality has

been satisfied.









48

Mobile Worker Communication System





6.1.2.2: Extendibility

The Framework is extensively engineered to maximise extendibility. As

discussed earlier in this document it is easy to extend the Framework to

encompass new Client and Modules. This functionality has been satisfied.







6.1.2.3: Responsive

This functionality can be broken down into two parts. Firstly the

responsiveness can be seen in the program operation i.e. the time it takes the

Server to respond to a command or in the responsiveness of the

WiredClient’s interface. Secondly responsiveness can be seen in the time

taken for the network communications. The program operation

responsiveness is unnoticeable to the user and can be measured in times

less then one second. However network communications responsiveness is

very subjective and relies on the responsiveness of the underlying network.

This type of responsiveness is outside of the control of the Communication

Framework. The responsiveness functionality has been satisfied.







6.1.3: Summary

Except for the completeness of the core message passing functionality, the

product met all product functional specification as defined by the problem

area. As stated, the Communication Framework can provide this functionality

however, the Mobile Device Handset fails to connect to the Communication

via GPRS/IP/UDP and hence messages can not be transmitted to and from

the Device.









49

Mobile Worker Communication System









50

Mobile Worker Communication System









7: Future Development

The major development of this product would be producing a working Mobile

Device Handset that was capable of connecting to the Communications

Framework. The Communications Framework is currently in a stable working

condition however there would be a number of future extensions possible.

♦ Addition of security features

♦ Enabling other backend databases

♦ A Framework control client







7.1: Security Features

Currently there isn’t any security features included in the Communications

Framework. It is foreseeable that there would be a number of security

features that would be desirable within this product. These could include:

♦ Restricting connections to authorised Clients i.e. a user name and

password or server challenge – response arrangement.

♦ Encryption of the information transferred. To implement this feature it

would be as simple as producing a new Module that handled the

encryption and decryption of the information to and from a client.







7.2: Backend Database

Currently the Communication Framework implements a Microsoft Access

database as its backend data storage solution. However the addition of

support for other database formats would be beneficial to the product i.e.

MySQL, Oracle.







7.3: Framework Control Client

The current operation of the Communications Framework allows all clients to

communicate with any other client. This default behaviour may not be

desirable because it allows for the abuse of the solution by using it like a







51

Mobile Worker Communication System





standard Instant Messenger. For example some offices do not allow

employees to use Instant Messenger applications however with the solution

installed it could be used as one. To work around this a Framework Control

Client could be developed to limit a client’s ability to communicate only to a

select few other clients as necessary to complete work tasks. What is being

proposed is basically to enforce a permissions structure on the

Communications Framework.









52

Mobile Worker Communication System









8: Conclusion



Keeping in communication in an effective and efficient manner has always

been a major issue and will always remain so. As the technology within this

problem area develops, new and interesting services will become available to

create new products.





This Thesis has been attempting to ease the difficulties associate with

communications in the specialised situation of mobile workers communicating

with an Office environment. To a large extent this solution has been

successful with the development of a fully functioning Communications

Framework. With more time and effort the Mobile Communications Handset

would also be able to communicate with the Framework and thus fulfil the

central function of the product to provide:





“Efficient and Effective communication for the Mobile Worker”





I believe that we are just beginning to see the advent of specialised

communications solutions for wireless applications.









53

Mobile Worker Communication System









54

Mobile Worker Communication System









Appendix A Code Listings









55

Mobile Worker Communication System







* @param mt the new module type

*/

Code Listing 1 - Module public void setModuleType(String mt);

/*

/**

* Module.java

* returns the name of the client connected via this module

*/

*

* @return the name of the client

import java.net.*;

*/

import java.io.*;

public String getName();

/**

/**

* The Module interface is the root class of the Module hierarchy

* sets the name of the client connected via this module

*

*

*

* @param n the new client name

* It defines the structure of any class that wishes to interact with the

*/

* Communication Framework as a Module. It is advised that any implementing

public void setName(String n);

* classes do not directly implement this interface but instead extend

* AbstractModule, UDPModule or

/**

TCPModule.

* returns the quiet status of this module

*

*

*

* @return the quiet status

* @see AbstractModule

*/

* @see UDPModule

public boolean getQuiet();

* @see TCPModule

*

/**

* @author Jeremy Thompson

* sets the quiet status of this client

*/

*

public interface Module {

* @param q the new quiet status

*/

/**

public void setQuiet(boolean q);

* returns the module type

*

/**

* @return the module type

* returns the module identifier

*/

*

public String getModuleType();

* @return the module identifier

*/

/**

public int getIdentifier();

* sets the module type

*

/**









56

Mobile Worker Communication System







* sets the identifier of this module

*

* @param i the new identifier

*/

public void setIdentifier(int i);



/**

* closes this module down and causes it to clean itself up

*/

public void close();



/**

* sends data to the client connected via this module

*

* @param data the data to be sent

* @throws Exception throws any exception cause during the send

*/

public void send(byte[] data) throws Exception;

}









57

Mobile Worker Communication System









/**

Code Listing 2 – AbstractModule * returns the module type

*

* @return the module type

/*

*/

* AbstractModule.java

public String getModuleType(){

*/

return moduleType;

}

/**

* This class represents an Abstract Module by implementing the Module interface.

/**

* It provides implementations of the basic methods of the Module interface.

* sets the module type

*

*

* @author Jeremy Thompson

* @param mt the module type

* @version 1.0

*/

*/

public void setModuleType(String mt){

public abstract class AbstractModule implements Module, Receiver {

moduleType = mt;

}

/** the identifier of this module */

public int ID;

/**

/** the name of the client connected to this module */

* return the name of the client connected to this module

public String name;

*

/** the type of module */

* @return the clients name

public String moduleType;

*/

/** the quiet status of this device */

public String getName(){

public boolean quiet;

return name;

}

/**

* Creates a new instance of AbstractModule

/**

*

* sets the name of the client connected to this module

* @param i the indentifier for this module

*

* @param n the name of the client connected to this module

* @param n the name of the client

* @param mt the module type

*/

*/

public void setName(String n){

public AbstractModule(int i, String n, String mt) {

name = n;

ID = i;

}

name = n;

moduleType = mt;

/**

quiet = false;

* returns the identifier of this module

}

*









58

Mobile Worker Communication System







* @return the modules identifier

*/

public int getIdentifier(){

return ID;

}



/**

* sets the modules identifier

*

* @param i the new identifier for this module

*/

public void setIdentifier(int i){

ID = i;

}



/**

* returns the quiet status of this module

*

* @return the quiet status

*/

public boolean getQuiet() {

return quiet;

}



/**

* sets the quiet status of this client

*

* @param q the new quiet status

*/

public void setQuiet(boolean q) {

quiet = q;

}

}









59

Mobile Worker Communication System







return new String[]{txfIP.getText(), txfPort.getText(), txfName.getText()};

}

Code Listing 3 – ConnectDialog

/** This method is called from within the constructor to

* initialize the form.

/*

* WARNING: Do NOT modify this code. The content of this method is

* ConnectDialog.java

* always regenerated by the Form Editor.

*/

*/

private void initComponents() {//GEN-BEGIN:initComponents

/**

java.awt.GridBagConstraints gridBagConstraints;

* A custom JDialog into which the user enters the Server details

*

buttonPanel = new javax.swing.JPanel();

* @author Jeremy Thompson

okButton = new javax.swing.JButton();

*/

cancelButton = new javax.swing.JButton();

public class ConnectDialog extends javax.swing.JDialog {

panDetails = new javax.swing.JPanel();

/** A return status code - returned if Cancel button has been pressed */

jLabel1 = new javax.swing.JLabel();

public static final int RET_CANCEL = 0;

jLabel2 = new javax.swing.JLabel();

/** A return status code - returned if OK button has been pressed */

jLabel3 = new javax.swing.JLabel();

public static final int RET_OK = 1;

txfIP = new javax.swing.JTextField();

txfPort = new javax.swing.JTextField();

/**

txfName = new javax.swing.JTextField();

* Creates new form ConnectDialog

jTextArea1 = new javax.swing.JTextArea();

*/

public ConnectDialog(java.awt.Frame parent, boolean modal) {

addWindowListener(new java.awt.event.WindowAdapter() {

super(parent, modal);

public void windowClosing(java.awt.event.WindowEvent evt) {

initComponents();

closeDialog(evt);

setSize(340, 190);

}

}

});

/** @return the return status of this dialog - one of RET_OK or RET_CANCEL */

buttonPanel.setLayout(new

public int getReturnStatus() {

java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

return returnStatus;

}

okButton.setText("OK");

okButton.addActionListener(new java.awt.event.ActionListener() {

/**

public void actionPerformed(java.awt.event.ActionEvent evt) {

* returns the information entered into the dialog

okButtonActionPerformed(evt);

*

}

*@return the details entered into the dialog [ip,port,name]

});

*/

public String[] getDetails(){

buttonPanel.add(okButton);









60

Mobile Worker Communication System







panDetails.add(txfIP, gridBagConstraints);

cancelButton.setText("Cancel");

cancelButton.addActionListener(new java.awt.event.ActionListener() { gridBagConstraints = new java.awt.GridBagConstraints();

public void actionPerformed(java.awt.event.ActionEvent evt) { gridBagConstraints.gridx = 1;

cancelButtonActionPerformed(evt); gridBagConstraints.gridy = 2;

} gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

}); gridBagConstraints.weightx = 1.0;

panDetails.add(txfPort, gridBagConstraints);

buttonPanel.add(cancelButton);

gridBagConstraints = new java.awt.GridBagConstraints();

getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH); gridBagConstraints.gridx = 1;

gridBagConstraints.gridy = 3;

panDetails.setLayout(new java.awt.GridBagLayout()); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.weightx = 1.0;

panDetails.setBorder(new javax.swing.border.TitledBorder("Server Details")); panDetails.add(txfName, gridBagConstraints);

jLabel1.setText("Server IP Address");

gridBagConstraints = new java.awt.GridBagConstraints(); jTextArea1.setBackground((java.awt.Color)

gridBagConstraints.gridx = 0; javax.swing.UIManager.getDefaults().get("Label.background"));

gridBagConstraints.gridy = 1; jTextArea1.setLineWrap(true);

gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; jTextArea1.setText("Please enter the server details and a name. The Server

panDetails.add(jLabel1, gridBagConstraints); IP Address can also be entered as a host name ie localhost.");

gridBagConstraints = new java.awt.GridBagConstraints();

jLabel2.setText("Server Port Number"); gridBagConstraints.gridwidth = 2;

gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.gridx = 0; panDetails.add(jTextArea1, gridBagConstraints);

gridBagConstraints.gridy = 2;

panDetails.add(jLabel2, gridBagConstraints); getContentPane().add(panDetails, java.awt.BorderLayout.CENTER);



jLabel3.setText("Client Name "); pack();

gridBagConstraints = new java.awt.GridBagConstraints(); }//GEN-END:initComponents

gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = 3; private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-

gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; FIRST:event_okButtonActionPerformed

panDetails.add(jLabel3, gridBagConstraints); doClose(RET_OK);

}//GEN-LAST:event_okButtonActionPerformed

gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 1; private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)

gridBagConstraints.gridy = 1; {//GEN-FIRST:event_cancelButtonActionPerformed

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; doClose(RET_CANCEL);

gridBagConstraints.weightx = 1.0; }//GEN-LAST:event_cancelButtonActionPerformed









61

Mobile Worker Communication System









/** Closes the dialog */

private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-

FIRST:event_closeDialog

doClose(RET_CANCEL);

}//GEN-LAST:event_closeDialog



private void doClose(int retStatus) {

returnStatus = retStatus;

setVisible(false);

dispose();

}



// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JPanel buttonPanel;

private javax.swing.JButton cancelButton;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JTextArea jTextArea1;

private javax.swing.JButton okButton;

private javax.swing.JPanel panDetails;

private javax.swing.JTextField txfIP;

private javax.swing.JTextField txfName;

private javax.swing.JTextField txfPort;

// End of variables declaration//GEN-END:variables



private int returnStatus = RET_CANCEL;

}









62

Mobile Worker Communication System









Code List 4 – DeviceException

/*

* DeviceException.java

*/



/**

* A custom Exception to register a Device Exception

*

* @author Jeremy Thompson

*/

public class DeviceException extends java.lang.Exception {



/**

* Creates a new instance of DeviceException without detail

message.

*/

public DeviceException() {

}





/**

* Constructs an instance of DeviceException with the specified

detail message.

* @param msg the detail message.

*/

public DeviceException(String msg) {

super(msg);

}

}









63

Mobile Worker Communication System







* For example the following input will create a TCPModule using the name

* "Client".

Code Listing 5 – ModuleFactory *

*

* "REGI Client TCPModule"

/*

*

* ModuleFactory.java

*

*/

*

* @param s the TCP socket the client is connected via

import java.net.*;

* @param parent the parent Server object

import java.io.*;

*

import java.lang.reflect.*;

* @return the newly created module.

*/

/**

public static Module createTCPModule(Socket s, Server parent){

* The ModuleFactory provides the mechanism for dynamically creating Modules

try{

* based on information passed to the Service using the REGI command using two

//read in the first line of text from the client

* static methods.

//must be the REGI command

* It facilitates the creation of Modules based on the TCPModule

BufferedReader in = new BufferedReader(new

* and UDPModule schemas.

InputStreamReader(s.getInputStream()));

*

//block for the client to transmit

*

String st = in.readLine();

* Classes that override these classes should not that the ModuleFactory expects

//remove the "REGI" section and then split it around the space

* the constructor of a module to use the same arguements as the two underlying

//this should mean that setup[0] contains the client name

* Modules.

//and setup[1] contains the module type

*

String[] setup = st.substring(5).split(" ");

* @author Jeremy Thompson

*

Module theMod;

* @see Module

//create the identifier for this module based on the hash of the name

* @see AbstractModule

//and the current time note this should garentue that identifiers are

* @see TCPModule

//unquie

* @see UDPModule

int id = setup[0].hashCode()+(int)System.currentTimeMillis();

*/

public class ModuleFactory {

//dynamically create the module using reflection

Class moduleDefinition;

/**

//the expected constructor format for a TCPModule based Module

* Creates a Module of the type requested which is based on the TCPModule.

Class[] argsClass = new Class[] {Integer.class, String.class, String.class,

* Specifically the incoming data is broken into the clientName and the

Socket.class, Server.class};

* moduleType.

Object[] argsData = new Object[] {new Integer(id), setup[0], setup[1], s,

*

parent};

*

Constructor argsConstructor;









64

Mobile Worker Communication System







* @param parent the parent Server object

//build the module *

moduleDefinition = Class.forName(setup[1]); * @return the newly created module.

argsConstructor = moduleDefinition.getConstructor(argsClass); */

theMod = (Module) argsConstructor.newInstance(argsData); public static Module createUDPModule(DatagramPacket pack, Server parent){

return theMod; try{

}catch(IOException ioe){ //get the data out of the packet

ioe.printStackTrace(); String st = new String(pack.getData());

} catch (ClassNotFoundException e) { //trim the packet of any excess white space

System.out.println(e); st = st.trim();

} catch (NoSuchMethodException e) { //split out the details

System.out.println(e); //setup[0] should contain the client name and setup[1] should

} catch (InstantiationException e) { //contain the module type

System.out.println(e); String[] setup = st.substring(5).split(" ");

} catch (IllegalAccessException e) {

System.out.println(e); Module theMod;

} catch (IllegalArgumentException e) { //create the identifier

System.out.println(e); int id = setup[0].hashCode()+(int)System.currentTimeMillis();

} catch (InvocationTargetException e) { //create the module using reflection

System.out.println(e); Class moduleDefinition;

} //the expected constructor for a Module based on the UDPModule class

return null; Class[] argsClass = new Class[] {Integer.class, String.class, String.class,

} InetSocketAddress.class, Server.class};

Object[] argsData = new Object[] {new Integer(id), setup[0], setup[1],

/** (InetSocketAddress)pack.getSocketAddress(), parent};

* Creates a Module of the type requested which is based on the UDPModule. Constructor argsConstructor;

* Specifically the incoming data is broken into the clientName and the

* moduleType. //build an instance of the new Module

* moduleDefinition = Class.forName(setup[1]);

* argsConstructor = moduleDefinition.getConstructor(argsClass);

* For example the following input will create a UDPModule using the name theMod = (Module) argsConstructor.newInstance(argsData);

* "aUDPClient". return theMod;

* } catch (ClassNotFoundException e) {

* System.out.println(e);

* "REGI aUDPClient UDPModule" } catch (NoSuchMethodException e) {

* System.out.println(e);

* } catch (InstantiationException e) {

* System.out.println(e);

* @param pack the datagram packet containing the connection details ie REGI } catch (IllegalAccessException e) {

string System.out.println(e);









65

Mobile Worker Communication System







} catch (IllegalArgumentException e) {

System.out.println(e);

} catch (InvocationTargetException e) {

System.out.println(e);

}

return null;

}

}









66

Mobile Worker Communication System









Code Listing 6 – TCPReceiver

/*

* TCPReceiver.java

*/

//import java.net.*;

/**

* A utility class used to define constant callback method for a multithreaded

* process. Used within this program extensively for the two ReceiveThread

classes

*

* @author Jeremy Thompson

*/

public interface Receiver {



/**

* Callback method that processes data produced by a separate thread

*

* @param in the string input to be processed

*

* @throws Exception any unhandled exception created during the processing of

* the data

*/

public void process(String in) throws Exception;



}









67

Mobile Worker Communication System







private InetSocketAddress server;

/** the identifier of the merchandise_manager client */

Code Listing 7 – SensorClient int manager_id;



/**

/*

* Creates new form SensorClient

* SensorClient.java

*

*/

* @param parent the sensor client is designed to run without a parent frame

* @param modal the modal status of the client

import java.net.*;

* @param s the socket address of the server to communicate with

import java.util.*;

*/

public SensorClient(java.awt.Frame parent, boolean modal, InetSocketAddress

/**

s) {

* SensorClient is a basic example of an embedded sensor that is designed to

super();

* communicate with the Communication Framework using UDP and a custom

//layout the GUI components

module

initComponents();

* called LoggingUDPModule. It mimicks an embedded vending

* machine sensor that informs a client called "merchandise_manager" that is

server = s;

* connected also connected to the system.

setSize(360,220);

*

//kills the client if the user presses the x

*

addWindowListener(new java.awt.event.WindowAdapter() {

* This class implements a very basic GUI to present data and allow for the starting

public void windowClosing(java.awt.event.WindowEvent evt) {

* or stopping of the client.

System.exit(0);

*

}

* @author Jeremy Thompson

});

* @see UDPModule

//setup the datagram socket to communicate with the server on and try and

* @see LoggingUDPModule

//connect to it

* @see WiredClient

try{

*/

sock = new DatagramSocket();

public class SensorClient extends javax.swing.JFrame {

sock.connect(server);

/** A return status code - returned if Cancel button has been pressed */

}catch(Exception e){

public static final int RET_CANCEL = 0;

e.printStackTrace();

/** A return status code - returned if OK button has been pressed */

}

public static final int RET_OK = 1;

timer = new Timer();

/** the UDP datagram socket to be used for communication */

}

private DatagramSocket sock;

/** a timer that triggers the client to send data */

/** @return the return status of this dialog - one of RET_OK or RET_CANCEL */

private Timer timer;

public int getReturnStatus() {

/** the address of the server*/

return returnStatus;









68

Mobile Worker Communication System







} gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 0;

/** This method is called from within the constructor to gridBagConstraints.gridy = 1;

* initialize the form. gridBagConstraints.gridwidth = 3;

* WARNING: Do NOT modify this code. The content of this method is gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

* always regenerated by the Form Editor. gridBagConstraints.weightx = 1.0;

*/ gridBagConstraints.weighty = 1.0;

private void initComponents() {//GEN-BEGIN:initComponents jPanel1.add(lblData, gridBagConstraints);

java.awt.GridBagConstraints gridBagConstraints;

butStart.setText("Start");

jPanel1 = new javax.swing.JPanel(); butStart.addActionListener(new java.awt.event.ActionListener() {

lblStatus = new javax.swing.JLabel(); public void actionPerformed(java.awt.event.ActionEvent evt) {

lblData = new javax.swing.JLabel(); butStartActionPerformed(evt);

butStart = new javax.swing.JButton(); }

butStop = new javax.swing.JButton(); });

jTextArea1 = new javax.swing.JTextArea();

jLabel1 = new javax.swing.JLabel(); gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 1;

getContentPane().setLayout(new java.awt.GridBagLayout()); gridBagConstraints.gridy = 3;

jPanel1.add(butStart, gridBagConstraints);

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent evt) { butStop.setText("Stop");

closeDialog(evt); butStop.addActionListener(new java.awt.event.ActionListener() {

} public void actionPerformed(java.awt.event.ActionEvent evt) {

}); butStopActionPerformed(evt);

}

jPanel1.setLayout(new java.awt.GridBagLayout()); });



jPanel1.setBorder(new javax.swing.border.TitledBorder("Embedded sensor gridBagConstraints = new java.awt.GridBagConstraints();

client")); gridBagConstraints.gridx = 2;

lblStatus.setText("Status"); gridBagConstraints.gridy = 3;

gridBagConstraints = new java.awt.GridBagConstraints(); jPanel1.add(butStop, gridBagConstraints);

gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = 2; jTextArea1.setEditable(false);

gridBagConstraints.gridwidth = 3; jTextArea1.setLineWrap(true);

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; jTextArea1.setText("This is an example of a embedded sensor device. For

gridBagConstraints.weightx = 1.0; example a senor embedded into a Drink vending machine which transmits refill

jPanel1.add(lblStatus, gridBagConstraints); requests and statistics using UDP. This example client tranmits information to

another client called \"merchandise_manager\" who represents the party interested

lblData.setText("Data"); in the information provided by the sensor.");









69

Mobile Worker Communication System







jTextArea1.setWrapStyleWord(true); //lookup the identifier of the merchandise_manager client

gridBagConstraints = new java.awt.GridBagConstraints(); out = "LOOK_N merchandise_manager";

gridBagConstraints.gridx = 0; //note the use of final because the packet is used within an anno inner class

gridBagConstraints.gridy = 0; final DatagramPacket p2 = new DatagramPacket(out.getBytes(),

gridBagConstraints.gridwidth = 3; out.length(), server);

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; //give the Server 4 seconds to setup the module and finally create

jPanel1.add(jTextArea1, gridBagConstraints); //the connection

timer.schedule(new TimerTask(){

gridBagConstraints = new java.awt.GridBagConstraints(); public void run(){

gridBagConstraints.gridx = 0; try{

gridBagConstraints.gridy = 3; sock.send(p1);

gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; sock.send(p2);

gridBagConstraints.ipadx = 200; }catch(Exception e){

jPanel1.add(jLabel1, gridBagConstraints); e.printStackTrace();

}

gridBagConstraints = new java.awt.GridBagConstraints(); }

gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = 0; }, 4000);

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; //must receive the merchandise_manager's id in a packet

getContentPane().add(jPanel1, gridBagConstraints); pack = new DatagramPacket(new byte[6000], 6000);

sock.receive(pack);

pack(); //get the data out of the packet and look for the id

}//GEN-END:initComponents String in = new String(pack.getData());

System.out.println(in);

private void butStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN- String ina[] = in.split(" ");

FIRST:event_butStartActionPerformed

//send a registration packet to login into the communication framework for(int i = 0; i

getDeviceIDByNameStmt, getDeviceIDStmt, setLastMsgStmt;

*

PreparedStatement getAllDeviceNamesStmt, getAllDeviceDetails,

* Initialise -> wait for connections / process client requests

getTimesStmt;

* -> create handling modules

*

/** Creates a new instance of Server */

* @author Jeremy Thompson

public Server(int tcpport, int udpport, String dburl) {

* @see Thesis document for more details

url = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ="+dburl;

*/

modules = new Hashtable();

public class Server {

udpModules = new ArrayList();

/** hashtable containing the actual module objects */

connect();

Hashtable modules;

try{

/**

socket = new ServerSocket(tcpport);

* an array list of udpModules although this is double handling udp modules

dSocket = new DatagramSocket(udpport);

* are handled completely differently to TCP modules

}catch(Exception e){

*/

e.printStackTrace();

ArrayList udpModules;

}

/** the socket to accept TCP connections on */

}

ServerSocket socket;

/** the datagram sockets to accept UDP connections (and communicate on) */

/**

DatagramSocket dSocket;

* @param args the command line arguments

/** will be true whilst the server is running */

*/









73

Mobile Worker Communication System







public static void main(String[] args){ *

System.out.println("Usage: Server tcpport udpport databaseurl"); * This method also sets up the prepared statements used to interact

Server s; * with the database.

try{ */

int tcpport = Integer.parseInt(args[0]); public void connect(){

int udpport = Integer.parseInt(args[1]);

System.out.println(args[2]); //load the JDBC to OBDC bridge for communication with the Access Database

s = new Server(tcpport, udpport, args[2]); try{

s.start(); Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );

}catch(Exception e){ System.out.println( "JdbcOdbcDriver, the Bridge has been loaded" );

System.out.println("Usage: Server tcpport udpport databaseurl"); }catch( Exception JDBC_ODBCdriver ){

} System.out.println( "Fail to load the JDBC_ODBCdriver: " +

} JDBC_ODBCdriver );

}

/**

* Kicks off the operation of the server //try to connect to the database

*/ try{

public void start(){ connection = DriverManager.getConnection( url, userid, password );

running = true; System.out.println("Setup connection successful");

//setup the thread to handle UDP communications //clear the existing table Device by dropping it and then making it

udpThread = new Server.UDPThread(); //again

udpThread.start(); Statement stmt = connection.createStatement( );

System.out.println("Creating table");

//wait for TCP connections stmt.executeUpdate("DROP TABLE Devices");

while(running){ stmt.executeUpdate("CREATE TABLE Devices (\n" +

try{ "DeviceID int,\n" +

Socket aSocket = socket.accept(); "DeviceName char(20),\n" +

//initiate a connection "ModuleType char(20),\n"+

connection(aSocket, null); "ModuleHash int,\n"+

}catch(Exception e){ "Connected time,\n" +

//on any exception kill the Server "LastMsgTime time\n" +

running = false; ")");

} stmt.close();

} //create the prepared statements

} //insert a new device

addDeviceStmt = connection.prepareStatement("insert into Devices values

/** (?,?,?,?,?,?)");

* Connects to the backend database. This method clears the existing //remove a device with the corresponding id

* Device table and creates a new one. removeDeviceStmt = connection.prepareStatement("delete from Devices

* where DeviceID = ?");









74

Mobile Worker Communication System







//get all the client names /**

getAllDeviceNamesStmt = connection.prepareStatement("select * Stops the server

DeviceName from Devices"); */

//get all details about the client using the supplied name public void stop(){

getDeviceNStmt = connection.prepareStatement("select * from Devices //stop modules

where DeviceName = ?"); running = false;

//get the clients id from the supplied name }

getDeviceIDByNameStmt = connection.prepareStatement("select DeviceID

from Devices where DeviceName = ?"); /**

//get all the details about a client using the supplied id * This method processes both UDP and TCP connections.

getDeviceIDStmt = connection.prepareStatement("select * from Devices *

where DeviceID = ?"); *

//update the last message field of the supplied device * If a TCP connection is received it is asssumed the the pack argument will

setLastMsgStmt = connection.prepareStatement("update Devices SET * be null and if a UDP connection then the s argument will be null.

LastMsgTime = ? where DeviceID = ?"); */

//get all details about every device public void connection(Socket s, DatagramPacket pack) throws

getAllDeviceDetails = connection.prepareStatement("select * from DeviceException{

Devices"); System.out.println("connection received");

//get the time details about the supplied device //create a new connection thread to handle the setup of the new connection

getTimesStmt = connection.prepareStatement("select Connected, ConnectionThread ct = new ConnectionThread(s, this, pack);

LastMsgTime from Devices where DeviceID = ?"); ct.start();

}

}catch( Exception connect ){

System.out.println( "Fail to setup the connection: " + connect ); /**

System.exit(1); * Registers a new module with the system

} *

} * @param m the new module

*

/** * @throws DeviceException when the device is already registered

* Disconnects from the backend Access Database */

*/ public void register(Module m) throws DeviceException{

public void disconnect(){ //get the module details

try{ int ident = m.getIdentifier();

connection.close(); String name = m.getName();

System.out.println( "closed" ); String moduleType = m.getModuleType();

}catch( Exception disconnect ){ //check already exists in the system

System.out.println( "Fail to close connection: " + disconnect ); if(modules.contains(new Integer(ident))) throw new DeviceException("Device

} already registered");

} else{

//if not then put into the appropiate data structures









75

Mobile Worker Communication System







if(m instanceof UDPModule)udpModules.add(m);

modules.put(new Integer(ident), m); /**

//and then enter the details into the database * Deregisters a device from the system and removes it

try{ *

addDeviceStmt.setInt(1,ident); * @param m the module to be removed

addDeviceStmt.setString(2,name); *

addDeviceStmt.setString(3,moduleType); * @return OK or Fail

addDeviceStmt.setInt(4,m.hashCode()); */

Time curTime = new Time(System.currentTimeMillis()); public String DREG(Module m){

addDeviceStmt.setTime(5,curTime); try{

addDeviceStmt.setTime(6,curTime); //close the module

addDeviceStmt.executeUpdate(); m.close();

}catch(SQLException sqle){ modules.remove(new Integer(m.getIdentifier()));

sqle.printStackTrace(); udpModules.remove(m);

} removeDeviceStmt.setInt(1,m.getIdentifier());

} removeDeviceStmt.executeUpdate();

System.out.println("registered device: "+ident); System.out.println("Deregistering "+m.getIdentifier());

//update all the clients about the new connection //update the clients to let them know of the removel

updateClients(); updateClients();

} return "OK";

}

/** catch(Exception e){

* looks up a module using the module id e.printStackTrace();

* return "FAIL Could not deregister device";

* @return the module using that id }

*/

public Module lookupID(int ident){ }

Module m = (Module)modules.get(new Integer(ident));

if(m == null){ /**

Iterator iter = udpModules.iterator(); * process a LOOK_I command from a client

while(iter.hasNext()){ *

Module m2 = (Module)iter.next(); * @param the identifier of the device to lookup

if(m2.getIdentifier() == ident){ *

m = m2; * @return a string contain the data in the DATA response format

break; */

} public String LOOK_I(int device_id){

} try{

} Module m = lookupID(device_id);

return m; //update the last msg time for the requesting client

} getTimesStmt.setInt(1, device_id);









76

Mobile Worker Communication System







ResultSet rs = getTimesStmt.executeQuery(); */

//get the data and format it public String LOOK_A(){

if(rs.next()){ try{

return "DATA "+m.getIdentifier()+" "+m.getName()+" "+rs.getTime(1)+" //get all the details and format

"+rs.getTime(2); ResultSet rs = getAllDeviceDetails.executeQuery();

} String out = "DATA ";

} while (rs.next( )) {

catch(Exception e){ out+=rs.getInt(1)+" "+rs.getString(2).trim()+" "+rs.getTime(5)+"

return "FAIL Could not find the specified device"; "+rs.getTime(6)+";";

} }

return "FAIL Could not find the specified device";

} rs.close();

return out;

/** }catch(Exception e){

* process a LOOK_N command from a client e.printStackTrace();

* }

* @param device_name the name of the device to lookup return "FAIL Server could not retrieve all device data";

* }

* @return a formated DATA response containing the data

*/ /**

public String LOOK_N(String device_name){ * process a SEND command from the client

try{ *

//gets the data from the database * @param send the module that is sending the message

getDeviceNStmt.setString(1, device_name); * @param device_id the id of the device to send to

ResultSet rs = getDeviceNStmt.executeQuery(); * @param msg the message to be sent

if(rs.next()){ */

return "DATA "+rs.getInt(1)+" "+rs.getString(2)+" "+rs.getTime(5)+" public String SEND(Module send, int device_id, String msg){

"+rs.getTime(6)+"\n"; try{

} //get the module to send to

} Module to = lookupID(device_id);

catch(Exception e){ //format a REC response

return "FAIL Could not find the specified device"; String out = "REC "+send.getIdentifier()+" "+msg;

}

return "FAIL Could not find the specified device"; try{

} //try sending it and then update the timestamps

to.send(out.getBytes());

/** setLastMsgStmt.setTime(1,new Time(System.currentTimeMillis()));

* process a LOOK_A command from the client setLastMsgStmt.setInt(2, send.getIdentifier());

* setLastMsgStmt.executeUpdate();

* @return a string formatted as a UPDATE response containning all data }catch(Exception e){









77

Mobile Worker Communication System







//if anything goes wrong deregister the offending device /**

DREG(to); * As udp is connectionless and transmitted via a single port must

} * allow for the udp based modules a method to transmit through

//update the clients */

updateClients(); public void udpSend(Module m, DatagramPacket pack){

return "OK"; try{

}catch(Exception e){ dSocket.send(pack);

e.printStackTrace(); }catch(Exception e){

return "FAIL "+e.getMessage(); DREG(m);

} }

} }



/** /*

* updates all of the clients with the current client list public String[] list(){

*/ ArrayList names = new ArrayList();

public void updateClients(){ try{

String output = "UPDATE "+LOOK_A(); ResultSet rs = getAllDeviceNamesStmt.executeQuery();

Enumeration e = modules.elements(); while (rs.next( )) {

Iterator iter = udpModules.iterator(); names.add(rs.getString(1));

Module aMod = null; }

try{ rs.close();

while(e.hasMoreElements()){ }catch(Exception e){

aMod = (Module)e.nextElement(); e.printStackTrace();

}

//send update only if module is not running quiet String[] sa = new String[names.size()];

if(!aMod.getQuiet())aMod.send(output.getBytes()); names.toArray(sa);

} return sa;

while(iter.hasNext()){ }*/

aMod = (Module)iter.next();

/**

//send update only if module is not running quiet * As connections can take awhile to form push the connection off onto

if(!aMod.getQuiet())aMod.send(output.getBytes()); * its own thread so the Server can continue to operate

} */

}catch(Exception ex){ private class ConnectionThread extends Thread{

System.out.println("deregistering"); /** the socket object - either tcp or udp */

DREG(aMod); Object sock;

} /** the Server */

Server parent;

} /** the datagram packet if it is a UDP connection */

DatagramPacket pack;









78

Mobile Worker Communication System







public void run(){

/** //indefinatly wait for packets

* creates a new ConnectionThread running = true;

* while(running){

* @param s the socket connecting try{

* @param p the parent Server //receive the packet

* @param pa the datagram packet if it is a udp connection DatagramPacket pack = new DatagramPacket(new byte[6000], 6000);

*/ dSocket.receive(pack);

ConnectionThread(Object s, Server p, DatagramPacket pa){ //try and get the module this packet should go to

sock = s; Module m = getModule(pack);

parent = p; //if the module couldnt be found then must be a new connection

pack = pa; if(m != null)

} //pass the incoming data to the module

((UDPModule)m).process((new String(pack.getData())).trim());

/** else connection(null, pack);

* starts the connection thread running }catch(Exception e){

*/ //stop running when an error occurs

public void run(){ running = false;

Module aModule = null; }

//socket will be null if it is a udp connection }

if(sock == null)aModule = ModuleFactory.createUDPModule(pack, parent); }

//else must be a TCP connection

else aModule = ModuleFactory.createTCPModule((Socket)sock, parent); /**

//register the newly created module * return a module that the pack corresponds to

try{ *

register(aModule); * @param pack the datagram packet

}catch(DeviceException de){ *

de.printStackTrace(); * @return the module is it exists

} */

} Module getModule(DatagramPacket pack){

} //get the socket address of the sender

InetSocketAddress addr = (InetSocketAddress)pack.getSocketAddress();

/** //try and match that address to a module that is already stored

* UDPThread waits for udp datagrams to arrive and then processes them Iterator iter = udpModules.iterator();

*/ while(iter.hasNext()){

private class UDPThread extends Thread{ UDPModule aMod = (UDPModule)iter.next();



/** if(aMod.getSocketAddress().getAddress().getHostAddress().equals(addr.getAddre

* the run method for this thread ss().getHostAddress())){

*/ if(aMod.getSocketAddress().getPort() == addr.getPort())









79

Mobile Worker Communication System







return aMod;

}

}

return null;

}



/**

* kills this thread

*/

public void kill(){

running = false;

}

}

}









80

Mobile Worker Communication System







* @param mt the module type

* @param s the TCP socket that the client is connected to

Code Listing 9 – TCPModule * @param p the parent server

*/

public TCPModule(Integer id, String name, String mt, Socket s, Server p) {

/*

//pass to the AbstractModule constructor

* TCPModule.java

super(id.intValue(), name, mt);

*/

parent = p;

sock = s;

import java.net.*;

try{

import java.io.*;

//start the receiving thread to receive data from the client

import java.util.*;

receiver = new TCPReceiveThread(this, sock);

receiver.start();

/**

//create the output writer to transmit to the client

* This class represents a TCP type module which handles a client

out = new PrintWriter(sock.getOutputStream(), true);

* connected via a TCP connection.

}

*

catch(IOException ioe){

* @author Jeremy Thompson

ioe.printStackTrace();

* @see Module

}

* @see AbstractModule

}

* @see UDPModule

* @see LoggingUDPModule

/**

*/

* Creates a new instance of TCPModule

public class TCPModule extends AbstractModule{

*

/** the input reader from the TCP connection */

* @param id the identifier of this module

BufferedReader in;

* @param name the name of the client connected via this module

/** output writer for the TCP connection */

* @param mt the module type

PrintWriter out;

* @param s the TCP socket that the client is connected to

/** the TCP socket */

* @param p the parent server

Socket sock;

*/

/** a thread that waits for input on the TCP connection */

public TCPModule(int id, String name, String mt, Socket s, Server p) {

TCPReceiveThread receiver;

//see above

/** the owner server */

super(id, name, mt);

Server parent;

parent = p;

sock = s;

/**

try{

* Creates a new instance of TCPModule

receiver = new TCPReceiveThread(this, sock);

*

receiver.start();

* @param id the identifier of this module

* @param name the name of the client connected via this module

out = new PrintWriter(sock.getOutputStream(), true);









81

Mobile Worker Communication System







} }

catch(IOException ioe){ else if(s.startsWith("DREG")){

ioe.printStackTrace(); String output = parent.DREG(this);

} send(output.getBytes());

} receiver.kill();

}

/** else if(s.startsWith("LOOK_I")){

* sends data to the client String output = parent.LOOK_I(Integer.parseInt(s.substring(7)));

* send(output.getBytes());

* @param data the data to be sent }

*/ else if(s.startsWith("SEND ")){

public void send(byte[] data) throws Exception{ String id = s.substring(5, s.indexOf(" ", 6));

String test = new String(data); String msg = s.substring(s.indexOf(" ", 6)+1);

out.println(test); String out = parent.SEND(this,Integer.parseInt(id), msg);

if(out.checkError())throw new Exception(); send(out.getBytes());

} }

else if(s.startsWith("QUIET")){

/** setQuiet(!getQuiet());

* closes this module down }

*/ }catch(Exception e){

public void close(){ e.printStackTrace();

//stop the receiver thread }

receiver.kill(); }

} }



/**

* process an incoming command from the client

*

* @param s the incoming data from the client

*/

public void process(String s) throws Exception {

try{

//envoke the appropriate method in the server

if(s.startsWith("LOOK_N ")){

send(parent.LOOK_N(s.substring(7)).getBytes());

}

else if(s.startsWith("LOOK_A")){

String output = parent.LOOK_A();

output = "UPDATE "+output;

send(output.getBytes());









82

Mobile Worker Communication System







}



Code Listing 10 – TCPReceiver /**

* Creates a new instance of TCPReceiver

*

/*

* @param p the parent interested in the incoming data

* TCPReceiver.java

* @param s the socket to listen on

*/

* @param group the thread group to add this thread too

*/

import java.util.*;

public TCPReceiveThread(ThreadGroup group, Receiver p, Socket s) {

import java.io.*;

super(group,"dummy");

import java.net.*;

parent = p;

import java.lang.*;

theSock = s;

setDaemon(true);

/**

}

* This is a utility class that waits for input on a TCP connection before

* passing it to a callback method in the owner

/**

*

* the run method that waits for data

* @author Jeremy Thompson

*/

*/

public void run(){

public class TCPReceiveThread extends Thread{

try{

/** the parent interested in the incoming data */

running = true;

Receiver parent;

//create the incoming reader for the TCP connection

/** the TCP socket */

socketIn = new BufferedReader(

Socket theSock;

new InputStreamReader(theSock.getInputStream()));

/** the incoming reader for the TCP connection */

BufferedReader socketIn;

while(running){

/** will be true while the thread is active */

//read in a line

boolean running;

String line = socketIn.readLine();

//will generate a null when the stream is closed hence kill

/**

if(line == null){

* Creates a new instance of TCPReceiver

running = false;

*

}

* @param p the parent interested in the incoming data

//send the data onto the parent

* @param s the socket to listen on

else parent.process(line);

*/

}

public TCPReceiveThread(Receiver p, Socket s) {

theSock.close();

parent = p;

}catch(Exception e){

theSock = s;

running = false;

setDaemon(true);

}









83

Mobile Worker Communication System







}



/**

* kills this thread

*/

public void kill(){

running = false;

}

}









84

Mobile Worker Communication System







//pass onto AbstractModules constructor

super(i.intValue(),n, mt);

Code Listing 11 – UDPModule address = addr;

parent = p;

}

/*

* UDPModule.java

/**

*/

* returns the socket address of the client connected via this module

*

import java.net.*;

* @return the socket address

*/

/**

InetSocketAddress getSocketAddress(){

* This class represents a module designed to handle a client connected

return address;

* via a udp connection.

}

*

* @author Jeremy Thompson

/**

*

* closes this module but because this is UDP no need to do anything

* @see Module

*/

* @see AbstractModule

public void close(){

* @see TCPModule

//no need to do anything because UDP is a connectionless protocol

* @see LoggingUDPModule

}

*/

public class UDPModule extends AbstractModule implements Receiver{

/**

/** the parent server */

* process an incoming command from the client

Server parent;

*

/** the socket address of the client */

* @param s the incoming data from the client

InetSocketAddress address;

*/

public void process(String s) throws Exception {

try{

/**

//envoke the appropriate method in the server

* Creates a new instance of UDPModule

if(s.startsWith("LOOK_N ")){

*

send(parent.LOOK_N(s.substring(7)).getBytes());

* @param i the identifier for this module

}

* @param n the name of the client connected via this module

else if(s.startsWith("LOOK_A")){

* @param mt the module type

String output = parent.LOOK_A();

* @param addr the address of the client

System.out.println(output);

* @param p the parent server

output = "UPDATE "+output;

*/

send(output.getBytes());

public UDPModule(Integer i, String n, String mt, InetSocketAddress addr, Server

}

p) {

else if(s.startsWith("DREG")){









85

Mobile Worker Communication System







String output = parent.DREG(this); }

send(output.getBytes());

}

else if(s.startsWith("LOOK_I")){

String output = parent.LOOK_I(Integer.parseInt(s.substring(7)));

send(output.getBytes());

}

else if(s.startsWith("SEND ")){

String id = s.substring(5, s.indexOf(" ", 6));

System.out.println("\""+id+"\"");

String msg = s.substring(s.indexOf(" ", 6)+1);

System.out.println("\""+msg+"\"");

String out = parent.SEND(this,Integer.parseInt(id), msg);

send(out.getBytes());

}

else if(s.startsWith("QUIET")){

setQuiet(!getQuiet());

}

}catch(Exception e){

e.printStackTrace();

}

}



/**

* sends data to the client connected via this module

*

* @param data the data to send

* @throws any exception that occurs

*/

public void send(byte[] data) throws Exception{

//trim off any white space

String trimed = new String(data).trim();

//pack the data into a datagram

DatagramPacket pack = new DatagramPacket(trimed.getBytes(),

trimed.length());

//set the destination address as the client

pack.setSocketAddress(address);

//use the server's datagram socket to send to the client

parent.udpSend(this, pack);

}









86

Mobile Worker Communication System







/**

* Creates a new instance of UDPReceiveThread

Code Listing 12 – UDPReceiveThread *

* @param p the interested party

* @param s the datagram socket to listen on

/*

* @param group the thread group to add this thread to

* UDPReceiveThread.java

*/

*/

public UDPReceiveThread(ThreadGroup group, Receiver p, DatagramSocket s)

{

import java.util.*;

super(group,"dummy");

import java.io.*;

parent = p;

import java.net.*;

theSock = s;

import java.lang.*;

setDaemon(true);

}

/**

* This is a utility class that waits for input from a UDP socket before

/**

* passing it to a callback method in the owner

* the operational run method of this thread

*

*/

* @author Jeremy Thompson

public void run(){

*/

try{

public class UDPReceiveThread extends Thread {

running = true;

/** the parent interested in the incoming data */

Receiver parent;

while(running){

/** the datagram socket being listened on */

//receive a pack

DatagramSocket theSock;

DatagramPacket pack = new DatagramPacket(new byte[6000],6000);

/** will be true while the thread is operating */

theSock.receive(pack);

boolean running;

//trim off any white space

String line = new String(pack.getData());

/**

line = line.trim();

* Creates a new instance of UDPReceiveThread

//pass to the parent

*

parent.process(line);

* @param p the interested party

}

* @param s the datagram socket to listen on

theSock.close();

*/

}catch(Exception e){

public UDPReceiveThread(Receiver p, DatagramSocket s) {

running = false;

parent = p;

}

theSock = s;

}

setDaemon(true);

}

/**

* kills this thread









87

Mobile Worker Communication System







*/

public void kill(){

running = false;

}

}









88

Mobile Worker Communication System







/** Creates new form WiredClient */

public WiredClient() {

Code Listing 13 – WiredClient //initalise interface components

initComponents();

/*

setSize(800,500);

* WiredClient.java

*/

devices = new Vector();

import java.util.*;

import java.text.*;

//update the device list

import java.awt.*;

lstDevices.setListData(devices);

import javax.swing.*;

lstDevices.setCellRenderer(new MyCellRenderer());

import javax.swing.event.*;

lstDevices.addListSelectionListener(this);

import java.net.*;

//create the blinking timer

import java.io.*;

timer = new java.util.Timer(true);

timer.scheduleAtFixedRate(new Blinker(), 750, 750);

/**

}

* This class represents a wired client for the office environment which is

* able to communicate with the Communications Framework of the Mobile Worker

/**

* Communication System. This client communicates via TCP.

* connects to the server on the details provided

*

*

*

* @param ip the ip of the server

* It employs a standard Java GUI as its interface.

* @param port the port number to connect to

*

* @param name the name to use

* @author Jeremy Thompson

*

*/

* @throws any exception that occurs

public class WiredClient extends javax.swing.JFrame implements

*/

ListSelectionListener, Receiver{

public void connect(String ip, int port, String name) throws Exception{

//create the socket to connect to the server

/** the list of devices provided by the server */

Socket s = new Socket();

Vector devices;

//connect to the server with a timeout of 20 seconds

/** a timer for event schedualing */

s.connect(new InetSocketAddress(InetAddress.getByName(ip), port),

java.util.Timer timer;

20000);

/** the tcp receiver thread for incoming data from the Server */

//start the receiver thread to listen for incoming data from the server

TCPReceiveThread receiver;

receiver = new TCPReceiveThread(this, s);

/** connection dialog for the user to input connection details */

receiver.start();

ConnectDialog dlgConnect = null;

//create the output writer

/** output writer to send data to the Server on */

out = new PrintWriter(s.getOutputStream(), true);

PrintWriter out;

//try and register on the server

register(name);









89

Mobile Worker Communication System







//give the server time to establish the connection before requesting a else txaMessages.setText(msgs);

//user list //update the device details pane

timer.schedule(new TimerTask(){ lblDeviceName.setText(d.getName());

public void run(){ lblDeviceID.setText(d.getID());

updateList(); lblConnected.setText(d.getConnectedStr());

} lblLastMsg.setText(d.getLastMsgStr());

}, 4000); }

} }



/** /**

* registers on the server using the name supplied * sends the server a LOOK_A command

* */

* @param name the name to use public void updateList(){

* @throws any exception sendToServer("LOOK_A");

*/ }

public void register(String name) throws Exception{

try{ /**

//format the REGI command * sends a string to the server

String regStr = "REGI "+name+" TCPModule"; *

//send it * @param output the string to be sent

sendToServer(regStr); */

} public void sendToServer(String output){

catch(Exception e){ try{

e.printStackTrace(); out.println(output);

} out.flush();

} }catch(Exception e){

e.printStackTrace();

/** }

* the event listener for the device list triggered when the user }

* changes a selection on the list.

*

* @param e the triggering event /** This method is called from within the constructor to

*/ * initialize the form.

public void valueChanged(ListSelectionEvent e){ * WARNING: Do NOT modify this code. The content of this method is

//get the selected device and display its messages * always regenerated by the Form Editor.

int index = lstDevices.getSelectedIndex(); */

if(index >= 0){ private void initComponents() {//GEN-BEGIN:initComponents

Device d = (Device) lstDevices.getSelectedValue(); java.awt.GridBagConstraints gridBagConstraints;

String msgs = d.getMessages();

if(msgs.equals(""))txaMessages.setText("no messages"); jPanel1 = new javax.swing.JPanel();









90

Mobile Worker Communication System







jLabel1 = new javax.swing.JLabel(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

lblDeviceName = new javax.swing.JLabel(); gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 2);

jLabel2 = new javax.swing.JLabel(); jPanel1.add(jLabel1, gridBagConstraints);

lblDeviceID = new javax.swing.JLabel();

jLabel4 = new javax.swing.JLabel(); lblDeviceName.setBorder(new javax.swing.border.LineBorder(new

lblLastMsg = new javax.swing.JLabel(); java.awt.Color(0, 0, 0), 1, true));

jLabel3 = new javax.swing.JLabel(); gridBagConstraints = new java.awt.GridBagConstraints();

lblConnected = new javax.swing.JLabel(); gridBagConstraints.gridx = 1;

jPanel2 = new javax.swing.JPanel(); gridBagConstraints.gridy = 0;

jScrollPane1 = new javax.swing.JScrollPane(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

lstDevices = new javax.swing.JList(); gridBagConstraints.weightx = 1.0;

jPanel3 = new javax.swing.JPanel(); gridBagConstraints.insets = new java.awt.Insets(1, 0, 0, 0);

jScrollPane2 = new javax.swing.JScrollPane(); jPanel1.add(lblDeviceName, gridBagConstraints);

txaMessages = new javax.swing.JTextArea();

jPanel4 = new javax.swing.JPanel(); jLabel2.setText("Device ID");

butSend = new javax.swing.JButton(); gridBagConstraints = new java.awt.GridBagConstraints();

txfSend = new javax.swing.JTextField(); gridBagConstraints.gridx = 0;

menuBar = new javax.swing.JMenuBar(); gridBagConstraints.gridy = 1;

fileMenu = new javax.swing.JMenu(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

exitMenuItem = new javax.swing.JMenuItem(); gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 2);

serverMenu = new javax.swing.JMenu(); jPanel1.add(jLabel2, gridBagConstraints);

mnuConnect = new javax.swing.JMenuItem();

mnuDisconnect = new javax.swing.JMenuItem(); lblDeviceID.setBorder(new javax.swing.border.LineBorder(new

helpMenu = new javax.swing.JMenu(); java.awt.Color(0, 0, 0), 1, true));

aboutMenuItem = new javax.swing.JMenuItem(); gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 1;

getContentPane().setLayout(new java.awt.GridBagLayout()); gridBagConstraints.gridy = 1;

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

setTitle("Mobile Woker Communication Package"); gridBagConstraints.weightx = 1.0;

addWindowListener(new java.awt.event.WindowAdapter() { gridBagConstraints.insets = new java.awt.Insets(1, 0, 0, 0);

public void windowClosing(java.awt.event.WindowEvent evt) { jPanel1.add(lblDeviceID, gridBagConstraints);

exitForm(evt);

} jLabel4.setText("Connected At");

}); gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 0;

jPanel1.setLayout(new java.awt.GridBagLayout()); gridBagConstraints.gridy = 2;

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

jPanel1.setBorder(new javax.swing.border.TitledBorder("Device Details")); gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 2);

jLabel1.setText("Device Name"); jPanel1.add(jLabel4, gridBagConstraints);

gridBagConstraints = new java.awt.GridBagConstraints();









91

Mobile Worker Communication System







lblLastMsg.setBorder(new javax.swing.border.LineBorder(new jScrollPane1.setViewportView(lstDevices);

java.awt.Color(0, 0, 0), 1, true));

gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 1; gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = 3; gridBagConstraints.gridy = 0;

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.weightx = 1.0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;

gridBagConstraints.insets = new java.awt.Insets(1, 0, 0, 0); jPanel2.add(jScrollPane1, gridBagConstraints);

jPanel1.add(lblLastMsg, gridBagConstraints);

gridBagConstraints = new java.awt.GridBagConstraints();

jLabel3.setText("Last Message At"); gridBagConstraints.gridx = 0;

gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0;

gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.gridy = 3; getContentPane().add(jPanel2, gridBagConstraints);

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 2); jPanel3.setLayout(new java.awt.GridBagLayout());

jPanel1.add(jLabel3, gridBagConstraints);

jPanel3.setBorder(new javax.swing.border.TitledBorder("Message"));

lblConnected.setBorder(new javax.swing.border.LineBorder(new jScrollPane2.setViewportView(txaMessages);

java.awt.Color(0, 0, 0), 1, true));

gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints = new java.awt.GridBagConstraints();

gridBagConstraints.gridx = 1; gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = 2; gridBagConstraints.gridy = 1;

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.gridwidth = 2;

gridBagConstraints.weightx = 1.0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.insets = new java.awt.Insets(1, 0, 0, 0); gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;

jPanel1.add(lblConnected, gridBagConstraints); gridBagConstraints.weightx = 1.0;

gridBagConstraints.weighty = 1.0;

gridBagConstraints = new java.awt.GridBagConstraints(); jPanel3.add(jScrollPane2, gridBagConstraints);

gridBagConstraints.gridx = 1;

gridBagConstraints.gridy = 0; jPanel4.setLayout(new java.awt.GridBagLayout());

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;

gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; butSend.setText("Send");

gridBagConstraints.weightx = 1.0; butSend.addActionListener(new java.awt.event.ActionListener() {

getContentPane().add(jPanel1, gridBagConstraints); public void actionPerformed(java.awt.event.ActionEvent evt) {

butSendActionPerformed(evt);

jPanel2.setLayout(new java.awt.GridBagLayout()); }

});

jPanel2.setBorder(new javax.swing.border.TitledBorder("Connected

Devices")); gridBagConstraints = new java.awt.GridBagConstraints();









92

Mobile Worker Communication System







gridBagConstraints.gridx = 1; exitMenuItemActionPerformed(evt);

gridBagConstraints.gridy = 0; }

jPanel4.add(butSend, gridBagConstraints); });



txfSend.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, fileMenu.add(exitMenuItem);

0, 0)));

gridBagConstraints = new java.awt.GridBagConstraints(); menuBar.add(fileMenu);

gridBagConstraints.gridx = 0;

gridBagConstraints.gridy = 0; serverMenu.setMnemonic('S');

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; serverMenu.setText("Server");

gridBagConstraints.weightx = 1.0; serverMenu.addActionListener(new java.awt.event.ActionListener() {

jPanel4.add(txfSend, gridBagConstraints); public void actionPerformed(java.awt.event.ActionEvent evt) {

serverMenuActionPerformed(evt);

gridBagConstraints = new java.awt.GridBagConstraints(); }

gridBagConstraints.gridx = 0; });

gridBagConstraints.gridy = 2;

gridBagConstraints.gridwidth = 2; mnuConnect.setMnemonic('C');

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; mnuConnect.setText("Connect");

jPanel3.add(jPanel4, gridBagConstraints); mnuConnect.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

gridBagConstraints = new java.awt.GridBagConstraints(); mnuConnectActionPerformed(evt);

gridBagConstraints.gridx = 0; }

gridBagConstraints.gridy = 1; });

gridBagConstraints.gridwidth = 2;

gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; serverMenu.add(mnuConnect);

gridBagConstraints.weightx = 1.0;

gridBagConstraints.weighty = 1.0; mnuDisconnect.setMnemonic('D');

getContentPane().add(jPanel3, gridBagConstraints); mnuDisconnect.setText("Disconnect");

mnuDisconnect.addActionListener(new java.awt.event.ActionListener() {

fileMenu.setMnemonic('F'); public void actionPerformed(java.awt.event.ActionEvent evt) {

fileMenu.setText("File"); mnuDisconnectActionPerformed(evt);

fileMenu.addActionListener(new java.awt.event.ActionListener() { }

public void actionPerformed(java.awt.event.ActionEvent evt) { });

fileMenuActionPerformed(evt);

} serverMenu.add(mnuDisconnect);

});

menuBar.add(serverMenu);

exitMenuItem.setText("Exit");

exitMenuItem.addActionListener(new java.awt.event.ActionListener() { helpMenu.setMnemonic('H');

public void actionPerformed(java.awt.event.ActionEvent evt) { helpMenu.setText("Help");









93

Mobile Worker Communication System







aboutMenuItem.setText("About"); connect(ip, port, name);

helpMenu.add(aboutMenuItem); this.setTitle("Mobile Woker Communication Package - " +name);



menuBar.add(helpMenu); }catch(Exception e){

JOptionPane.showMessageDialog(this,

setJMenuBar(menuBar); "The Server details you entered do not seem to be valid.",

"Connection Error", JOptionPane.ERROR_MESSAGE);

pack();

}//GEN-END:initComponents }



private void mnuDisconnectActionPerformed(java.awt.event.ActionEvent evt) }

{//GEN-FIRST:event_mnuDisconnectActionPerformed }//GEN-LAST:event_mnuConnectActionPerformed

sendToServer("DREG");

}//GEN-LAST:event_mnuDisconnectActionPerformed /**

* file menu event handler

private void serverMenuActionPerformed(java.awt.event.ActionEvent evt) */

{//GEN-FIRST:event_serverMenuActionPerformed private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-

// Add your handling code here: FIRST:event_fileMenuActionPerformed

}//GEN-LAST:event_serverMenuActionPerformed sendToServer("DREG");

System.exit(0);

/** }//GEN-LAST:event_fileMenuActionPerformed

* Action listener for the connect menu item. Triggered when that

* menu item is selected /**

*/ * Send button event handler

private void mnuConnectActionPerformed(java.awt.event.ActionEvent evt) */

{//GEN-FIRST:event_mnuConnectActionPerformed private void butSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-

//display a ConnectionDialog FIRST:event_butSendActionPerformed

dlgConnect = new ConnectDialog(this, true); //get the selected device

dlgConnect.show(); int index = lstDevices.getSelectedIndex();

int result = dlgConnect.getReturnStatus(); String msg = txfSend.getText();

if(result == ConnectDialog.RET_OK){ if(index >= 0 && !msg.equals("")){

try{ Device d = (Device) lstDevices.getSelectedValue();

//get the details entered and then parse them //send the supplied message to that device using a SEND command

String[] details = dlgConnect.getDetails(); sendToServer("SEND "+d.getID()+" "+msg);

String ip = details[0]; //add the message to the device object

d.addOwnMessage(msg);

int port = Integer.parseInt(details[1]); }

String name = details[2]; }//GEN-LAST:event_butSendActionPerformed

if(name.equals(""))throw new Exception();

//try to connect using the details supplied









94

Mobile Worker Communication System







private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) for(int i = 0; i "+msg);

*/ times.add(times.size(), new Date(System.currentTimeMillis()));

boolean getBlinkState(){ isMsg = true;

return blinkState; }

}

public String toString(){

/** return name+" ("+id+") ";

* Switch the blinking state of this device (to toggle the icon) }

*/ }

void toggleBlinkState(){

blinkState = !blinkState; /**

} * A timer task that blinks the icons in the devices list when there are new

* messages from that device.

/** */

* Return the new message status class Blinker extends TimerTask{









99

Mobile Worker Communication System







int index, // cell index

public void run() { boolean isSelected, // is the cell selected

//to remove user selection being lost if list boolean cellHasFocus) // the cell has the focus

//does not need to be updated {

boolean needToLoad = false; Device d = (Device)value;

Enumeration e = devices.elements(); setText(d.toString());

//check all the devices to see if they need to be changed //load the appropriate icon depending on the message status and the

while(e.hasMoreElements()){ //blink state

Device d = (Device) e.nextElement(); ImageIcon theIcon = noneIcon;

//if there are new message toggle the blink state and force if(d.isMessages()){

//the list to be redisplayed if(d.isNewMessages()){

if(d.isNewMessages()){ theIcon = (d.getBlinkState()) ? offIcon : onIcon;

d.toggleBlinkState(); }

needToLoad = true; else theIcon = offIcon;

} }

} setIcon(theIcon);

//reload the list with the new data and reset the selected item if (isSelected) {

int index = lstDevices.getSelectedIndex(); setBackground(list.getSelectionBackground());

if(needToLoad){ setForeground(list.getSelectionForeground());

lstDevices.setListData(devices); }

if(index > -1)lstDevices.setSelectedIndex(index); else {

} setBackground(list.getBackground());

} setForeground(list.getForeground());

} }

setEnabled(list.isEnabled());

/** setFont(list.getFont());

* A Cell render that displays an icon in the devices list setOpaque(true);

*/ return this;

class MyCellRenderer extends JLabel implements ListCellRenderer { }

}

ImageIcon noneIcon = new ImageIcon("images\\msg_none.gif"); }

ImageIcon onIcon = new ImageIcon("images\\msg_on.gif");

ImageIcon offIcon = new ImageIcon("images\\msg_off.gif");



// This is the only method defined by ListCellRenderer.

// We just reconfigure the JLabel each time we're called.



public Component getListCellRendererComponent(

JList list,

Object value, // value to display









100

Mobile Worker Communication System







Appendix B – Companion Disk

CD content

Location Description

/Code/Java Files Contains the source files for the

Communication Framework

/Code/Class Files Contains the compiled source files

using JDK 1.4

/docs Contains the documentation using the

javadoc tool

/33543635_thompson_thesis.pdf The thesis document









101

Mobile Worker Communication System









102

Mobile Worker Communication System





Bibliography



[1] S. Bennett, S. McRobb, R. Farmer, Object-Oriented Systems Analysis and

Design using UML, Mc Graw Hill, London 1999.





[2] C. Horstmann, G. Cornell, Core JAVA 2 Volume 1 – Fundamentals, Sun

Microsystems Press, 901 San Antonia Road, Palo Alto, California, 2001.





[3] C. Horstmann, G. Cornell, Core JAVA 2 Volume 2 – Advanced Features,

Sun Microsystems Press, 901 San Antonia Road, Palo Alto, California, 2000.





[4] Comparison of Novell Netware and TCP/IP protocol architectures,

www.odyssea.com/whats_new/tcpipnet/tcpipnet.html, September 2003.





[5] Introduction to TCP/IP, http://msdn.microsoft.com/library/en-

us/dniph/html/tcpipintro.asp, September 2003.





[6] An overview of TCP/IP Protocols and the Internet,

www.garykessler.net/library/tcpip.html, September 2003.





[7] ISO/OSI Network Model,

www.ussg.iu.edu/usail/network/nfs/network_layers.html, September 2003.





[8] B. Mansill (editor), Atomic Magazine, Issue 32, AJB Publishing,

September 2003.





[9] A. Parsons (editor), Australian Developer Magazine, Issue 1, Derwent

Howard, December 2002.





[10] B. Charny, Study: Global mobile phone use to double,

www.zdnet.com.au/techcentre/wireless/trends/story/0,2000050979,20276926,

00.htm, 07 August 2003.









103

Mobile Worker Communication System





[11] J. Pearce, 3G customers to number 50,000 within two weeks,

www.zdnet.com.au/newstech/communications/story/0,2000048620,20276859,

00.htm, 05 August 2003.





[12] A. Kidman, Who's buying 3G?,

www.zdnet.com.au/reviews/coolgear/mobiles/story/0,2000023537,20276851,0

0.htm, 05 August 2003.





[13] W. Chai, Japan gets to work on 4G comms,

www.zdnet.com.au/reviews/coolgear/mobiles/story/0,2000023537,20274387,0

0.htm, 12 May 2003.





[14] J. Pearce, Excited by 3G? Wait for 4G,

www.zdnet.com.au/newstech/communications/story/0,2000048620,20274231,

00.htm, 05 May 2003.





[15] A. Choong, Tech Guide: Wireless demystified,

www.zdnet.com.au/reviews/coolgear/mobiles/story/0,2000023537,20273908,0

0.htm, 23 April 2003.





[16] T. Dennis, Nokia says GSM is thrashing CDMA ,

www.theinquirer.net/?article=10774, Wednesday 30 July 2003.





[17] 3G and UMTS Frequently Asked Questions,

www.umtsworld.com/umts/faq.htm, 2003.





[18] W. Simpson (editor), RFC 1661 - The Point-to-Point Protocol (PPP),

Network Working Group, July 1994.





[19] RFC 793 - Transmission Control Protocol, Information Sciences Institute

University of Southern California, California, September 1981.





[20] J. Postel, RFC 768 - User Datagram Protocol, ISI, 28 August 1980.







104

Mobile Worker Communication System





[21] RFC 791 - Internet Protocol, Information Sciences Institute University of

Southern California

, California, September 1981.





[22] What is General Packet Radio Service?,

www.gsmworld.com/technology/gprs/1, GSM Association 1999 – 2003.





[23] GPRS Reference Page, protocols.com/pbook/gprs.htm, 2003.





[24] Amtel AT90S8515 manual, Amtel, Rev 0841G-09/01.





[25] Scott Lewis R, “Wireless PC based Services”, Prentice-Hall PTR Inc.,

2001









105



Related docs
Other docs by huanghengdong
2012_Vendor_Form_Wedding_Expo
Views: 0  |  Downloads: 0
SCOPE 1 GP letter v2.0 12Mar2007
Views: 0  |  Downloads: 0
Boston_immigration_records
Views: 2  |  Downloads: 0
PSC MATRIX of achievement 080709
Views: 0  |  Downloads: 0
Summary - CIRCA
Views: 0  |  Downloads: 0
ieee_wiley_ebooks_library_customer_title_list
Views: 0  |  Downloads: 0
2009-2010_ACC0044_fishers_772_07-dec-2009
Views: 1  |  Downloads: 0
FSP20111216-EN
Views: 0  |  Downloads: 0
Workshops
Views: 0  |  Downloads: 0
By registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!