139
Java Applications for a Bluetooth Platform By Benjamin Williams 2002 School of Information Technology and Electrical Engineering The University of Queensland

Java Application for Bluetooth

Embed Size (px)

Citation preview

Page 1: Java Application for Bluetooth

Java Applications for a Bluetooth Platform

By Benjamin Williams

2002

School of Information Technology and Electrical Engineering

The University of Queensland

Page 2: Java Application for Bluetooth

Benjamin Williams

5 Garson Place MC DOWALL, BRISBANE 4053

Ph. (07) 33533607 Mobile. 3842662046

[email protected] To the Head School of Information Technology and Electrical Engineering The University of Queensland St Lucia, QLD 4072 Dear Professor Kaplan, In accordance with the requirements of the degree of Bachelor of Engineering in the division of Electrical Engineering, I present the following thesis entitled ”Java applications for a Bluetooth Platform”. This work was performed under the supervision of Dr Adam Postula. 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 Benjamin Williams

Page 3: Java Application for Bluetooth

Acknowledgements Thank you to Dr Adam Postula, Henry Valk and Paul Logothetis for your assistance with this project. Thank you to Mum, Dad, Mark, Michael and Susan for your support through out the year.

Page 4: Java Application for Bluetooth

Abstract

In March 2002 a final year thesis project was undertaken based on a suggestion by

Henry Valk of HCV Wireless to investigate the development of a Java application for

a Bluetooth platform. The Bluetooth standard is a short range wireless technology

that allows different types of devices to form automatic, spontaneous networks. Java

applications are portable, secure and robust, which makes them suitable for users of

Bluetooth devices to wirelessly download and use to access a service.

There were three main aims of this project

• To analyse the features and limitations of Bluetooth and Java technology and

investigate what scenarios could benefit from a wireless application

implemented using this combination.

• To define a specification for an experimental Bluetooth/Java application and

design a solution to this specification using available technologies. The

solution will be a wireless system that provides a service of value to the end

user via a graphical interface.

• Implement the prototype solution and evaluate the value of the Bluetooth/Java

system from the perspective of the user in terms of the added convenience

from traditional methods of using the service.

It was decided that location based application would be implemented that would allow

a customer in an Airport café with a Bluetooth equipped mobile information device to

view the menu, place an order and check their flight status. A design was conceived

for implementing the application on a Compaq Ipaq 3870 that also incorporated using

web services middleware over the Bluetooth connection. The design was

implemented and with some changes a functional system was completed. However,

due to the limited resources available for developing Java applications using

Bluetooth on the Ipaq, the application performed poorly in terms of speed, reliability

and the added convenience for the user. It was concluded that further work was

Page 5: Java Application for Bluetooth

required to develop a more optimised Java/Bluetooth execution environment in order

to produce more compelling applications of value to the consumer.

Page 6: Java Application for Bluetooth

Table of Contents Part 1 – Introduction and basis for research ...................................................................1

1.1 Overview.............................................................................................................1 1.2 Introduction.........................................................................................................1 1.2 The Bluetooth Standard .......................................................................................2 1.2 Basis for the Project.............................................................................................5 1.3 Aims of the project ..............................................................................................7 1.4 Plan for delivering the project goals.....................................................................8

1.4.1 Research and analysis...................................................................................8 1.4.2 Design ..........................................................................................................9 1.4.3 Implementation .............................................................................................9 1.4.4 Evaluation ....................................................................................................9

Part 2 – Research and Analysis....................................................................................11 2.1 Overview...........................................................................................................11 2.2 Overview of the Bluetooth Specification ...........................................................11

2.2.1 The Radio ...................................................................................................11 2.2.2 The Baseband Layer ...................................................................................13 2.2.3 Link Manager Protocol...............................................................................14 2.2.4 Logical Link Control and Adaptation Protocol (L2CAP).............................14 2.2.5 Host Controller Interface ............................................................................15 2.2.6 RFCOMM...................................................................................................15 2.2.7 PPP ............................................................................................................15 2.2.6 OBEX .........................................................................................................16 2.2.7 Service Discovery Protocol.........................................................................16 2.2.8 The Bluetooth Profiles ................................................................................16 2.2.9 Generic Access Profile................................................................................17 2.2.10 Service Discovery Profile..........................................................................18 2.2.11 Serial Port Profile.....................................................................................18 2.2.12 Generic Object Exchange Profile ..............................................................18

2.3 Java 2 Micro Edition .........................................................................................18 2.3.1 Virtual Machine Layer................................................................................20 2.3.2 Configuration Layer ...................................................................................20 2.3.3 Profile Layer...............................................................................................20

2.4 Bluetooth API....................................................................................................21 2.5 Criteria for Bluetooth applications .....................................................................22

2.5.1 Strengths of the technology .........................................................................22 2.5.2 Limitations and restrictions of Bluetooth Technology..................................22

2.6 Other requirements for the experimental application..........................................24 2.7 Market for Bluetooth Applications.....................................................................24

2.7.1 Wireless Commerce ....................................................................................25 2.7.2 Location aware mobile commerce services .................................................26 2.7.3 Mobile Financial Application .....................................................................26 2.7.4 Mobile Advertising......................................................................................27 2.7.5 Proactive Service Management ...................................................................27 2.7.6 Product Location and Shopping ..................................................................27 2.7.7 Information services on public networks .....................................................28 2.7.8 Other non-commercial applications ............................................................28

Page 7: Java Application for Bluetooth

2.7.9 Ad-hoc networking and groupware .............................................................28 2.8 Non-functional requirements and criteria to evaluate the end product ................29

2.8.1 Added convenience .....................................................................................29 2.8.2 Speed ..........................................................................................................29 2.8.3 User Interface .............................................................................................29 2.8.4 Security.......................................................................................................30 2.8.5 Reliability ...................................................................................................30

2.9 Choice of application scenario ...........................................................................31 2.9 Critical evaluation of previous work performed on Bluetooth and Java Applications. ...........................................................................................................33

Part 3 – Design............................................................................................................37 3.1 Overview...........................................................................................................37 3.2 System architecture ...........................................................................................37 3.2 System Assumptions .........................................................................................37 3.3 Mobile Device Architecture...............................................................................39 3.4 Network Architecture ........................................................................................41 3.4 Server and Gateway Architecture ......................................................................44 3.5 Mobile device software selection and integration...............................................45

3.5.1 Java Virtual Machine..................................................................................45 3.5.2 Bluetooth Stacks .........................................................................................47 3.5.3 Operating System and JVM.........................................................................48

3.5 Distributed Mobile Services ..............................................................................48 3.6 Middleware Options ..........................................................................................52

3.6.1 COBRA.......................................................................................................52 3.6.2 Java Remote Method Invocation (RMI) .......................................................52 3.6.3 Web Services...............................................................................................53 3.6.4 Simple Object Access Protocol....................................................................53 3.6.5 Web Service Description Language.............................................................54 3.6.6 Universal Description, Discovery, and Integration (UDDI) ........................54 3.6.7 Incorporating Web Services into Bluetooth MIDP Applications ..................54

3.7 Client Application Design .................................................................................55 3.8 Server Design ....................................................................................................59 3.8 Design for the client Java Bluetooth interface ....................................................60 3.8 Gateway Design ................................................................................................64

Part 4 – Implementation ..............................................................................................66 4.1 Overview...........................................................................................................66 4.2 Implementation of the test Client MIDP Application and SOAP server..............66 4.3 Ipaq Setup .........................................................................................................67 4.4 Implementing the gateway.................................................................................68 4.5 Providing the Java interface to the Affix Bluetooth Stack ..................................69 4.6 Implementation and evaluation of the total system.............................................70

Part 5 – Evaluation......................................................................................................71 5.1 Overview...........................................................................................................71 5.2 Outcomes of the project.....................................................................................71 5.3 Evaluation of the final system design.................................................................72

5.3.1 Added convenience .....................................................................................72 5.3.2 Speed ..........................................................................................................72 5.3.3 User Interface .............................................................................................73 5.3.4 Security.......................................................................................................73 5.3.5 Reliability ...................................................................................................73

Page 8: Java Application for Bluetooth

5.4 Design Conclusions ...........................................................................................73 5.5 Future Recommendations ..................................................................................74

Bibliography ...............................................................................................................76 Appendix A – MIDP Application Screens ...................................................................80 Appendix B – MIDP Application Classes....................................................................83 Appendix C – MIDP Application Command Actions ..................................................86 Appendix D – MIDP Application Source Code ...........................................................88 Appendix E – Server Application Source Code .........................................................106 Appendix F – Gateway Source Code .........................................................................109 Appendix G – Old Java Bluetooth Interface Source Code..........................................116 Appendix H – Revised Java Bluetooth Interface Source Code ...................................123

Page 9: Java Application for Bluetooth

Table of Figures Figure 1. The Bluetooth Protocol Stack .......................................................................12 Figure 2. A Bluetooth Piconet .....................................................................................14 Figure 3. Profiles of the Bluetooth Specification .........................................................17 Figure 4. Java 2 Micro Edition Platform Architecture..................................................19 Figure 5. Topology of the network ..............................................................................39 Figure 6. Architecture of Software Components on the mobile device.........................40 Figure 7. Relationship between interfaces for the Generic Connection Framework......43 Figure 8. Network stacks for the gateway and mobile device.......................................45 Figure 9. Distributed System Layers............................................................................49 Figure 10. Using SOAP with TCP/IP/RFCOMM ........................................................55 Figure 11. Server architecture.....................................................................................59 Figure 12. Database Schema .......................................................................................60 Figure 13. The Interface for the Bluetooth connection classes ....................................62 Figure 14. RFCOMM Class........................................................................................63 Figure 15. The gateway process .................................................................................63 Figure 16. The application running in the emulator......................................................65

Page 10: Java Application for Bluetooth

1

Part 1 – Introduction and basis for research

1.1 Overview

This section provides an introduction to the basis for the topic and describes the aims

and objectives of the project. A plan for delivering the objectives is documented.

1.2 Introduction

Consumer electronics are continually growing into more sophisticated pieces of

equipment that have greater power in bringing convenience and enjoyment to everyday

life. Many different types of devices from mobile phones to air conditioners now

contain embedded microcontrollers to allow them to process information from there

surroundings. The continuing development in microchip production has seen computer

processing power follow Moore’s Law and double roughly every 18 months, in addition

further improvements in the miniaturisation of components. Designers have exploited

the trend of embedded processors becoming smaller and more powerful to develop new

lines of products and greater enhance the functionality of existing devices. The

Personal Digital Assistant or PDA is an example of how developments in

microprocessors have impacted on consumer products. The PDA originated as a device

to store phone numbers and addresses, and has evolved into devices such as the Ipaq

which is essentially a handheld computer with the power to do many of the tasks

performed by its desktop counterpart [13].

Along side the growth of computing power, recent times have seen large advances in

the area networking and communications, mainly fuelled by the explosion of the

Internet. These developments are now seeing smaller mobile devices such as mobile

phones and PDAs empowered with the capacity to connect to the Internet and exchange

information. Mobile phones equipped with the Wireless Access Protocol (WAP)

provide their user with the convenience of access to web information such as stock

quotes from almost any location covered by the cellular system. In a society that is

becoming increasing dependent on gathering and exchanging information, it is likely

Page 11: Java Application for Bluetooth

2

that there will be a continuing trend towards the development of personal information

devices that have added value to the user because of there ability to access and publish

data across networks.

Furthermore, with the continuing progress in computing and communication it is

believed that there will be a trend towards what is termed ‘Ubiquitous computing’ or

‘Persuasive computing’. This describes an environment where almost everything, from

our toasters to our cars, will have tiny embedded processors can communication

seamlessly with one another. Should Moore’s Law hold for another 15 years as

predicted, processors will become so small and inexpensive, they will be found in

everyday items such as clothes and pencils. These ‘smart’ devices will take advantage

of improvements in sensor technology to be able to gather information about there

environment and have spontaneous wireless networking capabilities to be able to

exchange this information to other systems. These systems will be able to process

relevant information and change the environment accordingly. This will all happen

unknowingly to the user to create unparalleled convenience [8].

1.2 The Bluetooth Standard

While widespread ubiquitous computing is still a future phenomena, the technology for

various devices to communicate wirelessly exists today in the form of the Bluetooth

specification. The Bluetooth standard is a short range wireless technology named after

the Viking King of Denmark 940-981AD Harald Blattand II, who was named

“Bluetooth” after the colour of his beard. Harald is credited with unifying the Vikings

of Norway and Denmark; hence his name is associated with a technology that aims to

create a standardised means for various types of devices to communicate over a wireless

connection. [9].

Bluetooth technology originated from Ericsson Mobile Communications, who were

searching for a means of developing a radio interface between mobile phones and

headset accessories. Researchers became aware that they could use the internationally

unlicensed ISM (industrial, scientific and medical) radio band for communicating

Page 12: Java Application for Bluetooth

3

between devices. They were able to develop a small embedded radio suitable for use in

small devices.

However, Ericsson saw the greater potential that this new technology offered. Not only

could mobile phones and headsets be wirelessly connected, but printers and PDAs and

virtually any other devices. Thus in 1998 along with Nokia, IBM, Toshiba and Intel,

they formed the Bluetooth Special Interest Group (SIG) to develop a global short range

radio standard. Version 1.0 of the Bluetooth Standard was completed in June 1999 at

almost 1500 pages in length.

The Bluetooth specification was designed to meet the following system requirements:

• Low cost

• Low power

• Universally adopted

• Must support a large variety of devices

• Must support automatic connections without user intervention

• Support voice and data communications

• Offer secure connections

The motivations for the development of the Bluetooth standard can be traced to both

immediate and future market needs. With proliferation of various computer devices and

peripherals, there is a short term demand to replace the cumbersome task of setting up

cable connections in order to allow these devices to exchange data. For example,

PDA’s and Laptops require cables to connect to a mobile phone that allows dial-up

internet access, while owners of desktop computers often have to put up with an

entanglement of cables for there printer, scanner, mouse, keyboard and other devices.

The Bluetooth specification was developed in order to create a standardised means of

utilising short range wireless technology to replace cable connections between varying

types of devices. The specification also seeks to make the connection process

automated, with the standard defining the means to find other nearby devices, search for

services and create the connection with minimal user intervention. This has the

potential to alleviate hassles associated with providing LAN and internet access to

Page 13: Java Application for Bluetooth

4

portable computers. Incorporating Bluetooth technology into an existing product is

expected increases its value to the consumer by making in easier to form connections to

other devices [7].

However, the Bluetooth specification is designed to offer the consumer much more than

cable replacement. Wireless technology removes many of the barriers imposed by

cables and allows for new types of networking ideas and products that could not be

offered by traditional wired networks. For instance, personal portable computers could

access public networks to take advantage of the services they may offer. A possible

scenario may be a shopping complex where a customer could access maps, directions,

catalogues and other information services from their portable computer. Offering such

access to public networks using personal computers is generally too impractical to be of

much value to the consumer using a wired system.

Because it is designed for creating standardised and automatic connections, Bluetooth

technology is well suited to the purpose of ad-hoc networking. Ad-hoc networking

refers to a network that can be formed automatically at a given time and place. Unlike

cellular systems, there is no need for a base station to co-ordinate the networking

between devices in an ad-hoc system Meetings and conferences are the obvious

situations where this type of networking has advantages. Members of a meeting could

form an ad-hoc network in any random conference room with portable computers and

be able to exchange documents and files to conduct the meeting more effectively. A

copy of the agenda and minute notes could be distributed to all members then and there

[6].

Furthermore, Bluetooth technology could provide a suitable stepping stone towards the

concept of persuasive computing. Bluetooth chips could be embedded in almost any

device, providing the spontaneous networking capabilities required to exchange

information with other entities in the system.

The full potential of Bluetooth however does not rest entirely with the specification.

While a number of profiles based around usage models for the technology are

documented, these profiles generally describe low level applications such as serial cable

emulation and file transfer that provide similar services to traditional wired networks.

Page 14: Java Application for Bluetooth

5

Though the specification is quite comprehensive in documenting protocols and profiles

to ensure standardised wireless connectivity, it generally only defines services at the

network, transport and, in some cases, presentation layers (with reference to the OSI

network model). Thus, software developers are required to create distributed

applications that utilise the wireless capabilities of Bluetooth technology in order to

deliver services of value to the user.

The Bluetooth standard has been designed to be compatible with existing networking

protocols (in part the Internet Protocol) to allow for existing network applications such

as web browsing to be used over a wireless connection. However, many of these

traditional applications have been developed under the assumptions they would be used

on fixed devices, and do not take advantage of the possibilities offered by mobile

computing. For example, consider the concept of location aware applications on a

mobile device that can access information on wireless services relevant to where the

person with the device is standing. This may the case of a person entering a store or

tourist attraction with a wireless PDA who wishes to look up the location of a particular

item.

Bluetooth technology is emerging with many development kits now available, but user

applications appear to be scarce. Thus, it is the overall essence of this project to

develop an application that realises some of the potential convenience and value

Bluetooth technology can offer.

1.2 Basis for the Project

The origin of this project stems from a discussion with Dr Adam Postula from the

School of ITEE at the University of Queensland and Henry Valk from HCV Wireless

about the viability of developing an application that could exploit Bluetooth technology.

The application would be intended to show case some of the benefits of this emerging

technology.

It was initially suggested that the application be developed as a graphical user interface

for the BlueMod device produced by HCV wireless. The BlueMod is essentially a

Page 15: Java Application for Bluetooth

6

Bluetooth enabled device with an embedded processor. The GUI would be designed in

concurrence with the development of an LCD display for the BlueMod. Due to the fact

the LCD screen for the BlueMod would be unavailable for 6 months, it was suggested

that the application be developed using the Java Language. Because of Java’s

portability, this would allow for the application to be developed on a desktop PC and

ported the BlueMod once the LCD screen was complete. It was decided that research

should also be conducted into finding an appropriate situation where a Bluetooth Java

application would provide real value and convenience to the user. It was concluded

from this meeting that the ultimate aim of the research project would be to develop a

Java application that utilised Bluetooth technology in providing a convenient service to

the end user via a graphical interface.

While Java was initially chosen as the application environment for practical purposes,

further research indicated that it was in fact well suited for wireless applications.

Sun Microsystems is marketing Java as excellent platform for developing wireless

applications because of three main advantages [15]

• Security

• Robustness

• Portability

Security

Because Java applications execute in a virtual machine architecture, they are safe from

causing harm to the host device. At worst, the applications can bring down the virtual

machine. Certain Java configurations use a security model known as the ‘sandbox

model’ to prevent application from access sensitive resources on the host.

Robustness

Features such garbage collection and the exception mechanisms improve the robustness

of application development. Additionally, the absence of direct memory manipulation

and strong typing generally means Java applications are less likely to fail.

Page 16: Java Application for Bluetooth

7

Portability

With wireless devices varying highly in system configurations, portability is an

important advantage. Application need only be written once and can then be

theoretically distributed to any Java enabled device. Portability is more critical in

embedded devices because the unlike desktop system, no one operating environment

(Microsoft Windows on Intel processors) dominates the market. The range of

processors and specialised operating systems makes the application environments across

embedded systems much more diverse [6].

These advantages are particularly important in considering the possibility of dynamic

‘over-the-air’ deployment of wireless applications. When downloading applications,

users will expect to be able to have confidence that the program will not cause harm or

disruption to their device, thus the security advantages of Java become essential.

Furthermore, due to the multitude of wireless devices, it would be almost impossible to

write a single application that could be downloaded and used by everyone, especially

without the need for additional configuration. Thus it necessary to have an application

environment that is portable across a large variety of devices.

In summary, it is hypothesised that utilising a combination of Bluetooth and Java

technology could allow developers to create universal wireless applications. Bluetooth

technology creates a standardised wireless networking framework for a variety of

different devices. The Java platform provides the portability, security and robustness

required to construct applications for mobile devices. This ultimately leads to more

valuable wireless products and services for the consumer. Thus, it seems worthwhile to

investigate what scenarios a consumer might benefit from this combination of

technologies and to develop an experimental system to evaluate this hypothesis.

1.3 Aims of the project

The three main aims are stated as for the purposes of providing direction to the project

are described as follows.

Page 17: Java Application for Bluetooth

8

• To analyse the features and limitations of Bluetooth and Java technology and

investigate what scenarios could benefit from a wireless application

implemented using this combination.

• To define a specification for an experimental Bluetooth/Java application and

design a solution to this specification using available technologies. The solution

will be a wireless system that provides a service of value to the end user via a

graphical interface.

• Implement the prototype solution and evaluate the value of the Bluetooth/Java

system from the perspective of the user in terms of the added convenience from

traditional methods of using the service.

Initially, a requirement of the experimental application was that it would run on the

BlueMod hardware supplied by HCV Wireless. However, due to problems with the

availability of the devices, a decision was made to use the Compaq Ipaq instead. In any

case, the final implementation of the system will use a mobile information device with

an LCD screen to provide services to the user.

1.4 Plan for delivering the project goals

The project will involve 4 stages: research and analysis, design, implementation and

evaluation.

1.4.1 Research and analysis

During this stage, research will be conducted into the Bluetooth specification and Java

technology with the following objectives:

• To obtain an understanding of Bluetooth technology and to identify its strengths

and limitations.

• To research Java technology with the view of using it with a Bluetooth device.

Page 18: Java Application for Bluetooth

9

• To research market opportunities for Bluetooth/Java applications and select an

appropriate application to design and implement.

• To develop a specification for the application.

• To identify criteria used to evaluate the value of the application to the end user.

• To critically examine previous work conducted on integrating Java and

Bluetooth technologies.

1.4.2 Design

During this stage, a design will be developed for the specification conceived in the

previous stage. In particular, the following outcomes of this stage are:

• Identification of architecture for the system required by the application.

• Assumptions are identified.

• Alternatives for the system components researched and evaluated.

• Documentation of a conceptual design for all system components and overall

design for integration of these components. This may include documentation of

design methodologies.

1.4.3 Implementation

During this stage, the actual implementation of the system design will take place.

Problems in implementing the original design will be identified and design

modifications conceived and tested. A working implementation that meets the

specification will hopefully be the outcome of this stage.

1.4.4 Evaluation

In this stage, the finished system will be evaluated for the value brought to the user. In

addition, the design methodologies will be evaluated as to there effectiveness in

delivering the required outcomes. Finally the project will be evaluated as to how well

the goals of the project were achieved.

Page 19: Java Application for Bluetooth

10

Page 20: Java Application for Bluetooth

11

Part 2 – Research and Analysis

2.1 Overview

This section of the project documents the work undertaken in the research and analysis

stage of the project. This includes the following

• An overview of Bluetooth technology and its strengths and weaknesses.

• Research into Java technology with the view of using it with a Bluetooth device.

• A critical examination previous work conducted on integrating these two

technologies.

• Research of market opportunities for Bluetooth/Java applications and the

selection of an appropriate application to design and implement.

• A specification for the application.

• Criteria used to evaluate the value of the application to the end user.

2.2 Overview of the Bluetooth Specification

In order to understand the capabilities of Bluetooth technology and how it can be used

for applications, it is necessary to understand how the various layers of the specification

work together to provide wireless connectivity for a variety of purposes. This section

briefly examines the Bluetooth specification [2]. The specification is divided into two

parts, the core and the profile sections. The core section specifies the protocols that

make up the Bluetooth stack. The profile section specifies profiles, which detail how

the various protocol layers should be used to implement a certain usage case. The

Bluetooth protocol stack is shown in figure 1.

2.2.1 The Radio

The Bluetooth radio operates in the unlicensed International Scientific and Medical

band of the frequency spectrum, which extends from 2.40-2.4835 GHz. This band is

Page 21: Java Application for Bluetooth

12

available worldwide, apart from a few countries which place restrictions on which parts

of the bands may be used.

The radio uses a frequency hopping spread spectrum system to minimise interference

from other devices that uses this band (such as microwave ovens). The band is divided

into 79 channels spaced at 1MHz and the radio performs frequency hops 1600 times per

second. The radio uses Gaussian Frequency Shift Modulation with a BT product of 0.5.

The Bluetooth specification allows for three classes of radios with different power

outputs as shown in Table 1.

Logical Link Control and Adaptation Protocol

RFCOMM Service Discovery Protocol

OBEX

Link Manager Protocol

Baseband Layer

Host Controller Interface

PPP

Radio

Figure 1. The Bluetooth Protocol Stack

Page 22: Java Application for Bluetooth

13

Table 1. Bluetooth Radio Classes

Radio Class Maximum Output power

(mW)

Approximate Range (m)

Class I 100 100

Class II 2.5 10

Class III 1 0.1

2.2.2 The Baseband Layer

The Baseband layer controls access to the physical medium through the Bluetooth radio.

Among the services this layer provides include:

• Inquiry procedures for discovering other devices

• Functionality for devices to synchronise their clocks and establish links on the

correct hopping frequencies.

• Error correction

• Data whitening

• Flow control

• Functions for generating encryption keys

A collection of Bluetooth devices sharing a single channel is known as a piconet. In

each piconet, one device acts as the master device, while the others as act as slaves. Up

to seven slaves can be active in a piconet. The Bluetooth standard uses Time Division

Multiplexing for communication across the link between the master and the slaves. The

channel is into time intervals know as slots corresponding to the duration of one

frequency hop. The slots are numbered corresponding to the master device’s clock and

the master uses even number slots to transmit while the slaves use odd numbered slots.

The Baseband supports two types of links, Synchronous Connection-Oriented (SCO)

and Asynchronous Connection-Less (ACL). SCO links is a circuit switched type link

between the master and a single slave that uses reserved slots at regular intervals to

generally carry voice information. ACL links do not use reserved slots, but rather are

Page 23: Java Application for Bluetooth

14

created by the master on a per slot basis to any of the slaves in the piconet. There are

five logical channels across these links that provide for control information, link

management information, user synchronous data, user asynchronous data and user

isosynchronous data.

2.2.3 Link Manager Protocol

The link manager protocol (LMP) is responsible for utilising the Baseband services to

carry out link setup, configuration and authentication and in addition may manage

optional quality of service and power control modes. The protocol defines protocol data

units (PDU) to carry out particular service operations. These PDUs are sent over the

link management channel.

2.2.4 Logical Link Control and Adaptation Protocol (L2CAP)

The Logical Link Control and Adaptation Protocol provides connection-orientated and

connectionless data services to the upper transport layer of the Bluetooth stack. The

protocol multiplexes upper layer data onto a single ACL connection and between two

devices. Should the device be the master of the piconet, then this data is then directed

Master Slave

Slave

Slave Figure 2. A Bluetooth Piconet

Page 24: Java Application for Bluetooth

15

to the appropriate slave. L2CAP provides segmentation and reassembly of the data to

fit into the required packet sizes of the Baseband. L2CAP is based around the idea of

channels, which represent a flow of information from a particular upper layer. Each end

of L2CAP channel is locally assigned a Channel Identifier (CID). Each layer above

L2CAP is assigned a Protocol Services Multiplexer (PSM) which is assigned to each

channel to allow for multiplexing.

2.2.5 Host Controller Interface

The lower layers of the Bluetooth stack - the Radio, Baseband and LMP – are usually

implemented as a separate hardware module that is added to the host device. Thus, if

the upper layers are implemented in software there needs to be a standard interface

between them and hardware. The Host Controller Interface (HCI) was designed to

allow a universal set of commands to access Bluetooth hardware. The HCI driver is a

software entity that resides on the host to provide access to the hardware via the HCI

over a transport bus. The transport bus can either be RS232, UART or USB. A HCI

controller on the Bluetooth hardware accepts and implements these commands from the

transport bus and forwards messages from the lower layers to the HCI driver.

2.2.6 RFCOMM

The RFCOMM layer, based on the TS 07.10 standard, emulates a RS232 serial

connection over a L2CAP channel. The standard supports multiple serial ports to be

emulated over a single connection.

2.2.7 PPP

The Point-to-Point protocol is used when mapping a Transmission Control

Protocol/Internet Protocol (TCP/IP) over a serial connection. The protocol is used in

the Bluetooth specification to allow TCP/IP connections to be made over a RFCOMM

emulated connection.

Page 25: Java Application for Bluetooth

16

2.2.6 OBEX

The Object Exchange standard (OBEX) was originally developed by the Infrared Data

Association but was reused by the Bluetooth specification. It specifies a protocol that

allows users to exchange data objects, and manage folders on remote devices. Objects

may be in the format of files or the vCard, vCalendar, vMessage and vNotes formats.

2.2.7 Service Discovery Protocol

The Service Discovery Protocol (SDP) is an important feature of the Bluetooth

standard. It allows for a device to query another device in order to discover the services

available over the Bluetooth connection. This is critical for the ad hoc networking and

automatic configuration capabilities of Bluetooth technology.

2.2.8 The Bluetooth Profiles

The Bluetooth Profiles are designed around envisaged usage models for the technology,

such as allowing LAN access and file transfer. The profiles specify how the protocols

of the Bluetooth stack should be used by applications to provide the services of a

particular usage model. This is necessary to minimise the chances of interoperability

problems between different implementations for a particular model. Note that some

authors (eg. [4]) believe the profiles still leave too much open interpretation to provide a

necessary level of interoperability. Nevertheless, the architecture of the Bluetooth

profiles in shown in figure 3. A profile encapsulated within another indicates a

dependency on the encapsulating profile. The main profiles applicable to application

development are discussed further.

Page 26: Java Application for Bluetooth

17

2.2.9 Generic Access Profile

Every Bluetooth device must at least support the Generic Access Profile (GAP). The

purpose of the profile is to define procedures so that any Bluetooth device can a least

connect to and discover the capabilities of another remote Bluetooth device, even if

both share no common application. The GAP specifies the following:

• User interface requirements regarding Bluetooth parameter representation and

connection procedures.

• The three modes of discoverability for devices – non-discoverable, limited

discoverable and general discoverable.

• Non-connectable and connectable modes.

Service Discovery Application Profile

Cordless Telephony Profile

Intercom Profile

Serial Port Profile

Dial-up Networking Profile

Fax Profile

Headset Profile

LAN Access Profile

Generic Object Exchange Profile

File transfer Profile

Object Push Profile

Synchronisation Profile

Generic Access Profile

Figure 3. Profiles of the Bluetooth Specification

Page 27: Java Application for Bluetooth

18

• Three security modes and authentication procedures.

• The general procedures for discovering the identity, name and basic capabilities

of other Bluetooth devices and making connections.

2.2.10 Service Discovery Profile

The purpose of the Service Discovery Profile is to define procedures for a service

discovery application to locate the services available to other devices. For the purposes

of this profile, a service discovery application is a specific user-initiated application

rather than an automated process. The profile covers searching for services by class and

attribute as well as browsing services.

2.2.11 Serial Port Profile

The serial port profile describes the procedures necessary to emulate a RS232 serial

connection. This is used to facilitate other applications that use serial connections.

These applications may be defined by the developer, or they may be defined by other

profiles such as dial-up networking, faxing and LAN access.

2.2.12 Generic Object Exchange Profile

The Generic Object Exchange Profile (GEOP) profile provides three main features to

the user application.

- Establishing an object exchange session.

- Pushing a data object.

- Pulling a data object.

Other features are defined by the profiles that use (GEOP) including the object push,

file transfer and synchronisation profiles.

2.3 Java 2 Micro Edition

With Bluetooth technology is generally incorporated into embedded devices that lack

the computational power, memory and storage capacity of the average desktop

Page 28: Java Application for Bluetooth

19

computer, it is necessary to use a Java platform with smaller performance requirements

than the standard version. In response to the growing embedded device market, Sun

Microsystems have developed the Java 2 Micro Edition (J2ME) platform, a Java

environment aimed at smaller systems with limited resources. Sun claims [15] that

J2ME supports many of the main features of the larger Java version including:

- Portability of code

- A high-level object oriented language

- Safe network delivery

The J2ME has the architecture shown in figure 4.

Embedded Device

Configuration

Host Operating System

Profile

Figure 4. Java 2 Micro Edition Platform Architecture

Virtual Machine

Java Platform

Page 29: Java Application for Bluetooth

20

2.3.1 Virtual Machine Layer

This Layer represents a virtual machine customised for a particular host operating

system. The virtual machine supports a particular configuration.

2.3.2 Configuration Layer

The configuration layer defines the minimum set of virtual machine features and class

libraries for a particular category of device. Currently there are two configurations for

the Java 2 Micro Edition platform. The Connected, Limited Device Configuration

(CLDC) is targeted at very small resource constrained devices with the following

characteristics:

- memory available to Java between 160kB and 512kB

- 16-bit or 32-bit processor

- battery powered

- sporadic network connectivity

This configuration is designed for the Kilobyte Virtual Machine (KVM), which is

smaller than the virtual machine used for Java 2 Standard Edition and optimised for

embedded systems. The CLDC supports a subset of capabilities of the Java 2 Standard

Edition. Examples of devices that may support this configuration are mobile phones

and pagers. Additionally, J2ME also defines the Connected Device Configuration for

more powerful embedded devices. This configuration is design for devices with over

2MB of memory and has a greater feature set than the CLDC.

2.3.3 Profile Layer

The profile layer is designed to add the additional functionality required on certain

categories or kinds of device. Sun describes this as providing support for ‘vertical’

market segments, in their belief that portability is most important across devices with

similar functional purposes. For example, a washing machine program should be

portable across washing machines, but not necessarily mobile phones.

Page 30: Java Application for Bluetooth

21

There is currently only one profile available for practical purposes, which is the Mobile

Information Device Profile (MIDP). As the name suggests, this profile is targeted at

mobile information devices, particularly mobile phones, and specifies a Java API for:

• Application lifecycle

• User interface

• Persistent storage

• Networking

• Timers

MIDP applications, known as ‘MIDlets’, are designed to be downloaded dynamically to

the mobile device and executed in a safe virtual machine environment. This idea has

already been extended to wireless systems where ‘wireless delivery’ is already proving

promising with internet enabled cellular phones. Over 23 million J2ME enabled mobile

phones were sold in 2003 [1]. A large proportion of these are expected to have

Bluetooth capabilities. Thus the MIDP could serve well for Bluetooth applications.

The ‘wireless delivery’ of MIDP applications could also be extended to using Bluetooth

connections rather than the cellular system.

2.4 Bluetooth API

Clearly for a Java application to maintain portability across a range of Bluetooth

devices, there must been some form of standardised API to access the services offered

by the Bluetooth stack. As part of the Java Community Process (JCP) a Java

Specification Request (JSR) was approved in October 2000 to design the architecture

and associated API’s to allow developers to utilise Bluetooth technology in Java

applications. An expert group was formed comprising of 21 members and lead by

Motorola to devise the specification. After significant public review inherent to the

Java Community Process, the final specification, JSR-82, was approved nearly one and

a half years later in March 2002 [5].

One of the main barriers to the prevalence of Bluetooth applications is the differences in

the interfaces between propriety Bluetooth stacks. The Bluetooth Java API is intended

Page 31: Java Application for Bluetooth

22

to help foster the development of Bluetooth applications by eliminating the need to

modify the applications for each stack. The API is targeted at devices with limited

memory and processing power because it was the opinion of the expert group that these

would be the first type of Bluetooth products to reach consumers in high volumes [17].

Hence, the API is based on the CLDC, which also allows for scalability to other Java

configurations. This means nearly all types of Bluetooth and Java devices can take

advantage of the API.

2.5 Criteria for Bluetooth applications

While Bluetooth has a lot of promising potential, it is not without limitations. Thus, as

part of the goals of this research to select a suitable experimental application, it is

necessary to construct a set of criteria to base this selection. The relative strengths and

weakness of the technology are examined in order to establish what scenarios could

benefit the most from it.

2.5.1 Strengths of the technology

The strengths of Bluetooth technology have already been discussed, but to summarise

the specification offers the following features:

- low power consumption

- low cost

- universal interoperability

- automatic connectivity with minimal user intervention

- ad-hoc networking

These features make the technology suitable for a range of short range wireless

applications in a host of consumer devices.

2.5.2 Limitations and restrictions of Bluetooth Technology

In chapter one of the Bluetooth Application Developer’s Guide by David Krammer,

Gordon McNutt, Brian Senese and Jennifer Bray [3] describes Bluetooth technology

from an ‘engineering’ perspective, highlighting what considerations must be made to

Page 32: Java Application for Bluetooth

23

determine if a Bluetooth product is practically viable. Six loosely defined conditions

are suggested that a product or application should adhere to:

• Adds usability, convenience and ease-of-use

The whole philosophy behind Bluetooth technology is that it adds value and

convenience to a product. Developers are warned to ensure that there end product will

actually deliver this, and not just be a wireless gimmick.

• Unaffected by interference and latency

Because of the nature of wireless communications, Bluetooth is susceptible to

interference from a range of other radiation sources, including microwave ovens,

thunderstorms and other wireless systems such as 802.11b. Hence, any Bluetooth

application must be able to tolerate occasional loss of connectivity. Obviously, this

makes the technology unsuitable for critical, high integrity systems.

• Tolerant of connection time overhead

The process of discovering other devices and forming connections can take a number of

seconds. Applications need to be able to handle this delay.

• Works with available bandwidth

Bluetooth connections have a maximum data rate of 723.2 Kbps, and the actual rate is

likely to be less that this. Applications must work sufficiently well within this data rate

limit.

• Can meet power requirements

Wired communication cables often also provide power to a device. If a wired device

become wireless, an alternative means of providing power must be found and power

consumption becomes more important. In the case where the device is already battery

operated, using the Bluetooth radio will shorten the battery life, so the application must

usable given the power constraints of the device.

Page 33: Java Application for Bluetooth

24

• The range of the wireless connection is adequate

Bluetooth is a short range technology, thus an application running on a Bluetooth device

must be operatable within the range of the receiver. The range of a Bluetooth

connection varies depending on the class of radio used and the environmental

conditions but is generally between 10m and 100m.

2.6 Other requirements for the experimental application

As was stated in the basis for this research project, the experimental application was to

be designed to incorporate a graphic user interface for the HCV Wireless BlueMod

device. The BlueMod, along with PDA’s and advanced mobile phones are classed by

Sun as “mobile information devices”. Consequently, the application would be

developed in accordance to the Mobile Information Device Profile and would need

suited to this profile. Thus, in exploring possible applications the search is limited to

those that would involve a ‘mobile information device’.

Because of problems with availability of the BlueMod, the Compaq Ipaq 3870 was

chosen as replacement hardware. One of the challenges for Sun in specifying profiles

for the J2ME platform is trading off uniformity against more offering powerful features.

Similarly, application developer must decide whether to take advantage of the more

powerful features in the more advanced profiles, or to design for portability across all

devices. Though the Ipaq is actually capable of running more powerful Java

configurations and profiles, the application will still be designed for the MIDP for

consistency throughout the project

2.7 Market for Bluetooth Applications

Beyond the usage models based on the profiles, suggestions for Bluetooth are numerous

and varied. This section aims to categorise the types of wireless services and

applications that could be served by Bluetooth technology. From these groups, an

experimental application will be selected that is appropriate to develop for the Java

MIDP

Page 34: Java Application for Bluetooth

25

2.7.1 Wireless Commerce

Undoubtedly, one of the largest demands for applications will be for wireless

commercial services. There is expected to be a huge market for wireless systems that

provide convenient methods for consumers and organisations to make transactions and

conduct business. There are two common business models for classifying the types of

wireless services. Business-to-consumer (B2C) models represent services offered to the

consumer by business organisations, while business-to-business (B2B) models involve

the services between business entities. B2C is expected to be more prevalent in wireless

systems [12].

Varshney and Vetter [23] describe a number of classes of emerging B2C applications.

These include:

- Mobile Financial Applications

- Mobile Advertising

- Mobile Inventory Management

- Proactive Service Management

- Product Locating and Shopping

- Wireless re-engineering

- Mobile Auctions

- Mobile Entertainment

- Mobile Office

- Mobile Education

- Wireless Data Centre

- Mobile Music

Many of these applications are more suited to cellular networks with a much larger

coverage area than the short-range Bluetooth standard, for example mobile education.

While cellular systems provide a greater coverage range, they currently support lower

bandwidths than Bluetooth technology and require more expensive infrastructure which

is passed on as a cost to the consumer. Thus, some wireless service providers may

Page 35: Java Application for Bluetooth

26

compete with cellular systems by providing similar services by Bluetooth “access

points” in selected highly populated places (such as shopping centres).

2.7.2 Location aware mobile commerce services

The short range of Bluetooth connections is not necessarily a limitation, but could

actually be exploited to provide the user with services relevant to where they are. For

example, a user who enters a store is most likely interested in accessing services

provided by the store, such as locating or purchasing a product. Kannan, Chnag and

Whinston [12] suggest these location aware services could a large impact on marketing,

because services could be provided at the point of need. Thus, the customer is provided

with services most relevant to their personal tastes and characteristics.

The short range and automatic connectivity features of Bluetooth technology would

make it an appropriate choice for location aware services. A Bluetooth equipped

personal device could form a connection when the user comes within proximity of an

access point. The Service discovery profile could then be used by the user to find

services at that location. Even further, the Java 2 Micro Edition platform could be

utilised as a standard and safe execution environment to dynamically deploy

applications at the point of need. The Mobile Information Device Profile could then be

used for the user interface to access the services. It would therefore be beneficial to

incorporate this concept into the experimental application.

In reviewing the classes of applications suggested by Varshney and Vetter [23], some

are more appropriate for a location-aware network than others and are discussed further.

2.7.3 Mobile Financial Application

Varshney and Vetter [23] suggest these applications will be among the most important

for wireless systems and could involve banking, money-transfer or making payments.

The idea of making wireless payments from within a store has been suggested by many

sources including Millar [9]. This could offer great convenience to the consumer who

could avoid waiting in queues, while the business would hope to achieve greater

revenues from offering the service. Payments to vending machines are another

Page 36: Java Application for Bluetooth

27

suggested application [23]. Since the consumer must be in the proximity of the machine

to make a purchase, this situation would be well suited to a location-aware application.

Some of the obvious requirements for mobile financial applications are security and

reliability [23], which are more difficult to implement in wireless systems.

2.7.4 Mobile Advertising

Mobile advertising is well suited to the idea of location-aware applications, because

advertisers could target a particular audience who may be in close proximity of a

business or product. A likely scenario is a shopping complex where the customer could

be providing with information about specials in surrounding shops. A more

controversial approach suggested by Varshney and Vetter [23] involves creating a

collection of information about a person inferred from what places they visit.

Advertisers could then target this person with products that appeal to them. Obviously,

they are numerous privacy issues raised in this approach.

2.7.5 Proactive Service Management

To illustrate this type of application, Varshney and Vetter [23] suggest a situation where

sensors in an automobile collect information about the wear of certain parts and react

via messages over a wireless connection to the owner’s mobile device. This idea could

be extended to control systems, where information and events could be sent wirelessly

to the user.

2.7.6 Product Location and Shopping

Some researchers advocate complex systems for locating products for the consumer

[12]. Bluetooth technology could be incorporated into this type of application as a

means to access a public wireless service in a shopping centre. The customer could

enter a product name into a mobile information device whilst near a Bluetooth access

point and receive directions to the nearest store stocking that product.

Page 37: Java Application for Bluetooth

28

2.7.7 Information services on public networks

With the aid of a mobile information device, consumers could browse or search through

extensive databases for information such as traffic reports, maps, stock quotes, news,

weather, entertainment guides, movie times and much more. Access to these types of

services is already possible through i-mode mobile phones in Japan. With location

based services, information could be filtered such that it is most relevant to where a

person is with their device.

2.7.8 Other non-commercial applications

There are also a number of applications for wireless technology outside commercial

purposes. Bray [3] suggests the medical sector is one area that could potentially benefit

in many ways. Non-critical measurements from sensors and other patient information

from database systems could be made instantly available on a doctor’s PDA. This could

allow for superior patient record management.

2.7.9 Ad-hoc networking and groupware

One of the strong features of Bluetooth technology is it allows for spontaneous ad-hoc

networks to be formed without existing infrastructure. This type of networking supports

the notion of peer-to-peer networking, where a mobile device acts as both a client and a

server. Kaminsky [6] makes some suggestions for peer-to-peer mobile applications

including

- Chatting and instant messaging between devices

- A ‘whiteboard’ application where a drawing appears on every user’s screen and

all users can make changes that become updated on the other users’ screens.

- Note taking for meetings where the notes are distributed to all other attendees

- Collaborative authoring of documents

Page 38: Java Application for Bluetooth

29

2.8 Non-functional requirements and criteria to evaluate the end product

In consistency with the aims governing the project, the completed experimental

application should provide a service of value to the consumer. In order to do this, it is

necessary to understand what attributes make a wireless service valuable to a consumer.

The following are suggested as attributes of value:

2.8.1 Added convenience

Probably the biggest reason a consumer would invest in a wireless technology is for

convenience. Using the wireless service should require less resources, time and effort

on the user’s part to achieve the desired task as compared to the more traditional way.

This could be the case in providing a product locator system, where the user only needs

to enter the name of the product, such as “eggs”, into a mobile information device

instead of searching through half the supermarket. However, Bray [3] warns that the

convenience of a service can be tarnished by complex connection issues and user

interfaces.

2.8.2 Speed

Closely tied to convenience, a wireless application is obviously more valuable if it is

responsive to the user requests. Applications should be designed to maximise speed

given the processor, memory and bandwidth limitations of the device hardware. The

speed of using the application in comparison to doing the task in the traditional way will

be considered in evaluating the final product.

2.8.3 User Interface

The user interface must be simple and effective to make a wireless application valuable.

Bray [3] suggests this is the biggest challenge in developing a wireless application.

The functional requirements of the project stipulate the user interface must consist of a

touch screen and the graphical components found in the Mobile Information Device

Profile. It will be necessary to work within these limitations to produce an application

that is effective in allowing the user to access the wireless services on offer. Sun

Page 39: Java Application for Bluetooth

30

Microsystems publishes the MIDP Whitepaper [21] that describes the differences

between requirements for user interfaces on desktop machines and consumer devices.

The following suggestions are made:

• Users of mobile devices expect a user interface far more simplistic than desktop

computers that requires less technical competence.

• The learning curve for the application should be instantaneous without the need

for manuals.

• Developers need to take care not to use systems that desktop users that for

granted and mobile device users may not be familiar with.

These suggestions will be considered in designing the graphic user interface for the

application from the MIDP components.

2.8.4 Security

Unlike wired networks which are often hidden behind walls, wireless signals can be

received by anyone within range of the transmitter making them far more susceptible to

unauthorised activities. Wireless applications that involve sensitive information or

access to sensitive resources (such as mobile financial services) must ensure a level of

security that the consumer is comfortable with. The Bluetooth standard specifies means

for providing encryption and authentication, however some researchers have pointed out

weakness in these approaches [22]. The experimental application will endeavour to

provide a suitable level of security which will depend on the type of application chosen.

The value of the application from a security perspective will be evaluated based on

known security weaknesses the measures required to facilitate unauthorised activity.

2.8.5 Reliability

A wireless application is obviously useless if it does not perform the task it is meant to.

The complexity of computer networks makes them inherently susceptible to sporadic

failure. In addition, wireless networks such as Bluetooth may experience connection

failures due to random interference and changes in the surrounding environment. The

MIDP whitepaper [21] suggests that mobile device users are less tolerant of random

Page 40: Java Application for Bluetooth

31

software failures than personal computer users. Hence, the appeal an application is

significantly dependent on the reliability of the software and the network system.

2.9 Choice of application scenario

It is decided that because of their revenue earning potential for business, wireless

commerce applications will likely be the most dominate of Bluetooth applications and

this type of application should be selected for experimental development. After

assessing the classes of wireless applications it has been asserted that given the short-

range and automated connectivity features of Bluetooth technology, it would be best

used with a location-aware application. Though peer-to-peer systems might become

prevalent in the future, the first types of applications are likely to be clients on

consumer mobile devices that access business-supplied services on larger servers.

Hence the experimental application will necessarily be represented by a client-server

model.

As has been discussed, there are virtually hundreds of scenarios where a Bluetooth

mobile commerce application could be useful. It is simply a creative process to decide

one that is suitable to develop for. One scenario suggested by Millar [9] that could

benefit from a range of mobile commerce applications is a traveller in an airport.

Because airports tend to be busy places, a traveller could find an application that allows

them to access flight information and make transactions very valuable. Thus, the

experimental application for this project will be based around providing services in an

airport environment.

Again, deciding what services to provide is a creative process for an experimental

application. Normally the software specification would be based on a business model,

however some ideas can be gathered from the traveller’s information section of the

Brisbane Airport Corporation’s website (http://www.bne.com.au/trav/index.html).

Some of the services listed include:

- arrival and departure times

- location of shops and services within the terminal

- weather information

- links to tourist and car hire information

Page 41: Java Application for Bluetooth

32

- links to reservation sites

- chatting among travellers

Besides information services, it would be beneficial to incorporate other types of mobile

commerce services, into the application. Thus, the scenario will be extended to include

a café in the airport terminal. Consumers who enter the café should be able to view and

order items from the menu from a mobile information device. In addition to the

services offered by the café, it will be assumed that the airport offers a service to check

on the status of a flight

Thus, the specification for the application is summarised as follows:

- A user should be able to view menu items as if they were reading a menu. Thus,

they should be able to browse through a list of names, descriptions and prices for

menu items. The menu is very dynamic, and must be retrieved from the wireless

server.

- A user should be able to create an order of items and submit this order.

- A user should be able to check the status of their flight.

Note originally it was also anticipated that the user could make a payment for their

order. However, research indicated that the security features of the J2ME and Bluetooth

specification are inadequate for such task at present [22].

This application would seem to fit the six criteria defined for Bluetooth applications.

Value is provided to user, because they save time in not having to wait in line or for a

waiter to order. Though undesirable, the application can tolerate the occasional loss of

connectivity due to interference. The power consumption will be device dependent, but

as the service would only be used for a few minutes, the extra power used by the

Bluetooth radio is unlikely to heavily impact on the battery life of the product. Long

connection times are undesirable but tolerable to a certain extent. The data exchanged

in the application is difficult to determine at this stage, but is expected to be comparable

to web browsing. The application is expected to be usable with in the data rate

limitation however this will be confirmed during the design stage of the project. Finally,

based the application is location sensitive and range limitation of Bluetooth radios is

acceptable.

Page 42: Java Application for Bluetooth

33

2.9 Critical evaluation of previous work performed on Bluetooth and Java

Applications.

Work towards the development of Java based Bluetooth application starts from the

specifications [2] for both technologies. Both the core and profile parts of the Bluetooth

specification are available from the Bluetooth SIG website and combined total over

1500 pages. Other resources, including Miller & Bisdikian [10], Muller [11] and

Kansal [7] provide a helpful companion for information about the specification. The

specification itself is the authority that defines Bluetooth technology and all

development will conform to the specification.

With respect to Java, there are three specifications relevant to this project that will be

followed. The Connection, Limited Device Configuration Specification Version 1.0a.

by Sun Microsystems [18] defines the specification for the CLDC while Mobile

Information Device Profile (JSR-37) JCP Specification Java 2 Platform, Micro

Edition, 1.0a [19] specifies the MIDP Profile. Both these documents will be used as the

authority for using and developing for the CLDC and MIDP. Furthermore, the JSR-82

[5] specifies the Bluetooth API for the CLDC. The JSR-82, MIDP and CLDC

specifications are essential for maintaining the portability of Java Bluetooth applications

and will be adhered to throughout the project. The Java Community Process governing

the development of these standards is likely to ensure they serve their purpose well, but

they will still be subjected to evaluation as part of this project.

Unlike most other resources that simply provide and explanation of the Bluetooth

specification, Bray [3] is targeted at providing information for developers planning to

develop Bluetooth applications. It provides a critical examination by experienced

Bluetooth developers of the Bluetooth standard in terms of its technical strengths and

weaknesses. This resource provides criteria for the suitability of Bluetooth applications

which has been adopted for this project. In addition, it provides examples of how to

utilise the various features of the Bluetooth stack with applications.

The commercial potential of integrating Java and Bluetooth technologies is already

being exploited by a number of companies. San-Diego based Zucotto Wireless has

developed a Java based JSR-82 compatible Bluetooth stack that it has incorporated into

Page 43: Java Application for Bluetooth

34

its WHITEboard™ SDK for creating J2ME applications. The Zucotto stack is written

entirely in Java, rather than being an API to native code. This is surprising, given native

code is generally has a faster execution time. However, Zucotto also has been

developing processors that can run Java bytecode, so their strategy would seem to be to

alleviate the relatively slow execution of Java code. Unfortunately, the Zucotto stack is

too expensive to be used in this project [20].

Irish based Rococo is also a heavy proponent of Bluetooth and Java based technology

with CEO Karl McCabe highlighting the portability and mobility aspects of Java being

important to development of Bluetooth applications [24]. Rococo produce

Java/Bluetooth simulators and development kits, but again these are unavailable to the

project. Both these commercial interests show shared ideas regarding the potential for

Java and Bluetooth, but no development towards the project objectives can really be

leveraged. Likewise, these companies do not provide any critical feedback on the

results of their applications development.

One of the few documented cases of research into the development of a Java/Bluetooth

application involves an investigation by the US Army into a replacement for the

Handheld Terminal Unit (HTU) which is a portable device used by soldiers to send

tactical information about the battlefield back to the commander’s computer. The army

was considering using portable, platform independent software systems to reduce the

costs of maintaining proprietary software. The HTU was to be replaced by a less

expensive PDA which connected wirelessly to a more powerful transceiver. The results

of the project indicated that Bluetooth was not a viable alternative to use with Java

because basically no implementation of Bluetooth API’s existed. Research conducted

for this project agrees with this conclusion, as implementations of Bluetooth API’s for

Java are scarce and none are freely available [25]. This project intends to extend this

work by implementing certain portions of the JSR-82 API to use for the experimental

application.

Finally, there has been two projects undertaken that research the application of

Bluetooth and Java to distributed applications. The Anhinga Project [6] undertaken at

Rochester Institute of Technology is looking at developing middleware for ad-hoc

networks based on Bluetooth and Java technology. The philosophy behind this project

Page 44: Java Application for Bluetooth

35

is that software developed for ad-hoc networks requires a many-to-many

communication paradigm not well supported by existing middleware systems. Thus,

the Anhinga Project aims to produce a middleware system, based on Bluetooth and Java

technology, for supporting ‘groupware’ applications. A large part of this project

involves implementation of a many-to-many network protocol that works over the

Bluetooth HCI. The protocol provides an interface to a modified version of a CLDC

virtual machine.

There are a few differences between the aims of the Anhinga Project and this thesis

project. The Anhinga Project focuses on peer-to-peer networking, while the

experimental application developed for this project is necessarily based on a client-

server architecture. Secondly, the Anhinga Project seems to disregard the JSR-82 API

in favour of developing a middleware API to be used by applications. Finally, the

Anhinga Project looks at using Sun’s JINI as part of there middleware system. This

requires additions to the CLDC specification. Thus the Anhinga project does not

conform well to the JSR-82/MIDP/CLDC standards and appears more directed towards

developing a specific middleware standard. In contrast, this thesis project focused on

delivering an application and system that conforms to the MIDP/CLDC and JSR-82

standards to ensure portability. Despite the differences, both this thesis project and the

Anhinga Project are consistent in there motivations to deliver portable software

environments for short range wireless systems.

The use of JINI for Java and Bluetooth systems is also addressed by Hashman and

Knudsen [4]. This paper, produced by the company PsiNaptic, claims a scaled down

version of JINI has been produced, but it is unclear whether this configuration can work

with the CLDC.

To summarise, this project is based on the work done in producing the Bluetooth,

CLDC, MIDP and JSR-82 specifications. The project takes the next step in addressing

how these technologies can be integrated and will produce an experimental application

as proof of concept. The book Bluetooth application developer's guide : the short

range interconnect solution [5] is one of the few resources available on developing

Bluetooth applications and will be used to assist in the design process. Previous work

towards developing Java and Bluetooth applications is limited, but suggests

Page 45: Java Application for Bluetooth

36

implementations of a Bluetooth API are difficult to obtain and the CLDC limits the

capacity for the dynamic downloading of applications.

Page 46: Java Application for Bluetooth

37

Part 3 – Design

3.1 Overview

This section documents the design process taken in delivering the outcomes of this

project. This includes the follows steps:

• Identification of architecture for the system required by the application is

undertaken.

• Assumptions are identified.

• Alternatives for the system components researched and evaluated.

• Documentation of a conceptual design for all system components and overall

design for integration of these components. This may include documentation of

design methodologies.

3.2 System architecture

A block diagram of the system proposed in this project is shown in figure 5. In normal

operation, the mobile client discovers the gateway and forms a connection when the

user brings the device into proximity. The user can then discover and browse through

services available from the gateway. Should the user wish to use a service, the mobile

device will automatically download and run any Java MIDP applications needed to use

that service.

3.2 System Assumptions

Before beginning the design process, some assumptions are made to simplify the

considerations that must be made.

• The gateway and the server are not necessarily the same device. The services

available at the location of the access point are not necessarily located on the

access point device. Access points are likely to be small devices that connect

wireless devices to a wireless network.

Page 47: Java Application for Bluetooth

38

• Access to information services from the gateway to the servers will be assumed

to be IP based over an unknown LAN topology. In a real scenario, the

characteristics of the LAN would impact on the performance of the delivery of

the Bluetooth services. However, the experimental system will use a dedicated

point to point connection that is faster than the Bluetooth connection, so the

LAN will be assumed to have no bearing on the client application’s

performance.

• The experimental application will use a single server to model the café and

airport server to save on resources and because the topology of the network is

assumed to be irrelevant.

• As the focus of the project is on the client and wireless networking issues, the

design of applications to utilise and change data on the server will not be

considered. These types of applications are common and no pioneering work is

required is this area.

• A single gateway is assumed to provide wireless access for the whole café.

Depending on the size of the café and the class of the Bluetooth radios used by

the mobile device and the gateway, this may or may not be a realistic situation.

From the server’s perspective, multiple gateways would simply have multiple IP

addresses, so if say a web server was to be used, this would have little impact on

the design. Likewise, the mobile device only would need to locate and connect

to one gateway to access the service. However to keep resource requirements

for the project low and single gateway design will be used.

• The initial design will assume only one client will connect to the gateway at any

one time. This is an unrealistic expectation but because of resource limitations it

is infeasible to test multiple clients trying to access the server simultaneously.

The system may theoretically be able to support multiple clients through.

• The mobile device will be a PDA capable of running the MIDP.

Page 48: Java Application for Bluetooth

39

3.3 Mobile Device Architecture

The architecture of the software components of the mobile device is an important part

of the system. The focus of the design of the architecture is to provide compatibility

with the JSR-82/MIDP/CLDC standards to demonstrate how these standards can be

used for a universal Bluetooth application environment. The mobile device will be a

Compaq Ipaq 3780 which has an in built Bluetooth Radio. The Ipaq 3780 was chosen as

the development device on the basis of availability and that it could meet MIDP

Wireless connection

Café Server Airport Server

Bluetooth Access Point Mobile

Device

Figure 5. Topology of the network

Local Area Network

Page 49: Java Application for Bluetooth

40

requirements. It was also very similar to the BlueMod, the original devices to be used

in the project. It is a very powerful device for a PDA, with 32MB of onboard SDRAM

memory and a 206 MHz Strong Arm processor. This should ensure plenty of flexibility

for development work.

The architecture for the mobile device is shown in figure 6. The components

surrounded by a dashed line will be implemented by third party developers and selected

from alternatives as part of the complete software integration design. The components

surrounded by a bold line will be implemented as part of the research. Starting from the

bottom, the device hardware includes the Ipaq 3870 and the built Bluetooth radio. The

next layer, the operating system, will be dependant the Java Virtual Machines and

Bluetooth stacks available. The options include Microsoft’s PocketPC 2002 which

comes standard with the Ipaq or a version of Linux. Part of the operating system layer

Device Hardware

Operating System Bluetooth Stack

Java Virtual Machine

CLDC Classes Bluetooth API Classes

Java Application Manager / Service

manager

Java native Bluetooth

library

MIDP Classes

Application

Figure 6. Architecture of Software Components on the mobile device

Page 50: Java Application for Bluetooth

41

will include a Bluetooth stack that provides services for the application to access via the

Java Bluetooth API. The Bluetooth stack will be selected on the basis of cost, features

and programmers interface.

The next layer noted is the Java Application Manager / Service manager component.

This component is defined in the MIDP specification [19] as “an environment in which

the MIDlet is installed, started, stopped, and uninstalled”. In this project, the role of this

component is extended to discovering what services are available to the user at a

particular location and to retrieve and run the necessary Java program. This component

would exist as a process in the operating system.

The remaining layers are responsible for providing the actual Java execution

environment. A virtual machine is required that is capable of supporting the CLDC and

MIDP API. In the layers above the virtual machine are the Java Classes required by the

CLDC and MIDP. Additionally, a Bluetooth API will need to be incorporated into the

Java execution environment. The API will include two parts, native methods

incorporated into the virtual machine layer that interface with the Bluetooth Stack and

Java classes to provide the JSR-82 API for the application to use. An alternative would

be to use a Java based Bluetooth stack, such as the as one developed by Zucotto [20],

this is very expensive to obtain and to difficult to implement given resource and time

restraints of this project. The native and Java Bluetooth libraries will therefore need to

be implemented because they are not readily available to developers. Only the parts of

the JSR-82 API required by the application will be developed.

3.4 Network Architecture

In developing network architecture for the system, compliance with the Bluetooth and

JSR-82 specification is paramount to ensuring interoperability between the server and

all Bluetooth/MIDP devices. The Bluetooth specification provides two profiles that

could be utilised for the application. Firstly the serial port profile could be used, with

the mobile device exchanging data with the gateway over an emulated serial connection.

Secondly, the LAN Access profile is also possibility, in which case the mobile device

would establish a PPP connection over an emulated serial connection with the gateway.

Page 51: Java Application for Bluetooth

42

This would provide the mobile device with the network services of the Internet

Protocol, including an IP address, so it could then use a transport layer such as TCP or

UDP to communicate with the gateway and/or the server. Another option worth

mentioning is the Personal Area Networking (PAN) profile. This profile was developed

by the Bluetooth SIG after the release of version 1.1 of the Bluetooth specification. The

PAN specifies a means for creating IP based ad-hoc networks. It uses the Bluetooth

Network Encapsulation Protocol (BNEP) which specifies how IP packets can be

encapsulated in the L2CAP layer.

A closer examination of the CLDC, MIDP and JSR-82 specifications reveals that the

Serial Port Profile may be the best option. To examine why, one must first consider the

abstractions used by the CLDC and MIDP in creating connections. Traditionally, the

Java 2 Standard edition provide networking support through the java.net.* networking

package. However, this package is too expansive to fit into the resource constrained

devices targeted by the Java 2 Micro Edition. Thus, a new framework for making

connections was developed known as Generic Connection Framework (GCF). As the

name suggests, connections formed with the (GCF) are done so through the same

interface regardless of type of connection being formed. A connection is formed by

using the ‘open’ method of the ‘Connector’ class in the javax.microedition.io package.

The open method returns an instance of the class Connection that may be cast to one of

the interfaces shown in figure 7. The interface will depend on the type of connection

being formed.

The open method accepts a URI in the form of <scheme>:<address>;<parameters>

which specifies what type of connection to open (reference). For example the following

code opens a socket connection to port 1216 on the local host:

OutputConnection os = (OutputConnection) Connector.open(“socket://localhost:8080”);

In a similar manner, a connection to a serial port can be open with the following code.

OutputConnection os = (OutputConnection) Connector.open(“comm:0;baudrate=9600”);

Page 52: Java Application for Bluetooth

43

The JSR-82 API continues the philosophy of forming connections through the same

interface. The following code forms a virtual serial connection using the Serial Port

Profile:

OutputConnection os = (OutputConnection) Connector.open(“bt_spp://234523452345:7);

Using this code will establish a RFCOMM connection to the server machine with a

Bluetooth Address of 234523452345 on channel 7. The inquiry service specified by the

GAP could initially be used to location the server in the vicinity of the device and

determine its address while the SDP could be used to discovery a particular service

offered by the server and the RFCOMM channel that service is located on. Thus, the

Serial Port Profile is a viable choice between the MIDP/CLDC client and the server.

Connection

Output Connection

Stream Connection

Stream Notifier Connection

Input Connection

Datagram Connection

Content Connection

Figure 7. Relationship between interfaces for the Generic Connection Framework (based on figure 13.8 in Java 2 Micro Edition by James P. White and David A. Hemphill [26]).

Page 53: Java Application for Bluetooth

44

However, using the LAN access profile with MIDP/CLDC is more difficult. The LAN

profile requires the PPP, IP and TCP protocols to be used over a RFCOMM connection.

These protocols are normally implemented by native code incorporated into the

operating system. The problem is that using the GCF, there is no way to specify what

serial connection to use for the TCP/IP/PPP protocols or how that connection is formed.

In fact, neither the CLDC nor the MIDP specify that a socket connection is mandatory,

though it is included in Sun’s reference implementation. The MIDP only specifies a

HTTP connection is mandatory.

Thus some problems are evident. The device may have more than one interface

available for both HTTP and TCP/IP. For example, a Bluetooth equipped mobile phone

may have access to a TCP/IP connection through a nearby Bluetooth access point or by

the cellular system. In some cases, using one interface may be more appropriate than

using another. The cost for the consumer to use the Bluetooth access point may be less

than to use the cellular system and some services may only be available from the access

point. There is no specification for how to make a socket connection using the GCF,

nor is there any specified way for identifying which interface to use for a socket or

HTTP connection. Thus making socket connections in CLDC applications undermines

their portability. The PPP/TCP/IP protocols could be implemented over a RFCOMM

connection in Java as part of the application, but this would be slow and result in a large

increase in the program size.

As there is no standardised means for using the LAN Access Profile in Java, it is

decided to use the Serial Port Profile for communication between the mobile device and

the gateway. The protocol stack for the network is shown in figure 8. The gateway acts

as a type of application proxy, redirecting data from the serial transport layer over a

TCP/IP connection to the server.

3.4 Server and Gateway Architecture

The server architecture will be dependant on the middleware chosen for interacting with

the client, but will basically consist of a server application running on a Windows or

Linux based x86 personal computer. The gateway will have similar basic architecture,

Page 54: Java Application for Bluetooth

45

but will have additional Bluetooth hardware and drivers. A gateway program running

on top of a Linux or Windows operating system will use the Bluetooth hardware and

network interfaces to direct information from the client to the server. Ideally, the

gateway software should reside on a small, specifically designed embedded system to

make it cheaper and so that it could be place discretely at strategic locations. However,

for development purposes, a desktop system will be used.

3.5 Mobile device software selection and integration

This section describes the alternatives for Java Virtual Machine, Bluetooth stack and

operating system to be used on the Compaq Ipaq 3870 and how these software

components will be integrated to provide the necessary functionality on the mobile

device.

3.5.1 Java Virtual Machine

Ideally, the JVM (or KVM) used should be CLDC and MIDP compliant and speed

optimised for the Ipaq. Unfortunately however, there are only a few alternatives for a

JVM running on the Ipaq and none of these are particularly well suited to running

MIDlets. Firstly, it would be possible to compile and port the Sun Microsystems

Gateway

RFCOMM

L2CAP

LMP

Physical (Wireless) Layer

LMP

L2CAP

RFCOMM

Application Layer Application Layer

TCP

IP

Data Link Layer

Physical Layer

Application Layer

Mobile Device

Physical (Wireless) Layer

Figure 8. Network stacks for the gateway and mobile device

Page 55: Java Application for Bluetooth

46

reference implementation of the KVM for the CLDC to the Ipaq. However, the MIDP

also have to be ported and this would be a significant software engineering task because

a MIDP implementation is largely dependant on graphics hardware of a device. The

graphical hardware on the Ipaq varies considerably from a desktop system which the

reference implementation is aimed at. The IBM J9 CLDC virtual machine is another

option, but again no MIDP support is provided. The only MIDP/CLDC virtual machine

that appears to be produced for the Ipaq is called Jeode and is developed Insignia

(http://www.insignia.com). However, this machine is only released to embedded

developers under contractual agreements and is not readily available for academic

purposes.

As was mentioned, the Ipaq is actually capable of running more featured versions of

Java that the MIDP/CLDC. While there is lack of MIDP/CLDC JVMs for the Ipaq,

there exists JVMs for other versions of Java such as Personal Java. Thus, another

approach that can be taken is to emulate the MIDP and CLDC on top of another virtual

machine. This can be achieved using the ME4SE classes written by Stefan Haustein

(http://me4se.org). These classes are open source and allow MIDP applications to be

run on the Standard Edition Java platform. Thus they could be used to create an MIDP

environment on the Ipaq in conjunction with a standard edition virtual machine. This is

not an ideal solution that has obvious performance and security drawbacks. However, it

is the fastest alternative to providing a MIDP execution environment

There are four standard JVMs that are available on the Ipaq. Firstly, there is SavaJE

system that is compatible with Java 2 Standard Edition version 1.3

(http://www.savaje.com). However, this application environment incorporates the

virtual machine into the operating system, which prohibits interfacing the virtual

machine with a Bluetooth stack. It is therefore not very suitable. Another option is the

Personal Java virtual machine that was produced by Sun. It runs on top of Windows CE

or Windows PocketPC. Personal Java is an outdated Java platform for embedded

system that has been superseded by Java 2 Micro Edition. This virtual machine is

therefore no longer officially supported by Sun. Insignia also provide a Personal Java

compliant JVM that come standard with the Ipaq. Finally, there is the Kaffe Virtual

Machine, which started as an open source project and was ported to the Ipaq by Kero

van Gelder. It is available from www.handhelds.org. Though not officially endorsed

Page 56: Java Application for Bluetooth

47

by Sun, Kaffe is compatible with Java version 1.1 with some minor inconsistencies.

While any of these three JVMs in combination with the ME4SE classes would be

suitable for running MIDlets, choosing which one to use will be dependent on what

operating system is required for the Bluetooth stack.

3.5.2 Bluetooth Stacks

Because PocketPC comes standard with the Ipaq, it is desirable to use a Bluetooth stack

for this operating system to avoid having to go to trouble install Linux. Unfortunately,

there are no Bluetooth stacks for PocketPC that are freely available and include support

for developers. In contrast, there are three open source Linux based stacks that are more

suitable for academic research.

The OpenBT project is an open source Bluetooth driver for Linux originally developed

by Axis for use in their access point products (www.axis.com). The stack provides

support for all the basic protocols, including HCI, LMP, L2CAP, SDP and RFCOMM.

The serial port profile is supported, with the interface to RFCOMM channels provided

by a TTY driver. Once a connection has been established, data can be transferred in the

same way as using a serial port TTY. The OpenBT stack has been successfully ported

to the Arm architecture so it could be used for the Ipaq. However Bray [3] cautions that

the stack is not fully featured and the following problems exist:

• There is no way to bind a RFCOMM channel to specific a server application.

• There is no means to dynamically register services with the SDP.

• Applications must create and parse they own SDP requests and responses.

• Protocols are not featured above L2CAP other than RFCOMM.

Some of these problems, such as the inability to dynamic alter the services database for

the SDP, exist with the server features and would not impact on the client side.

Another consideration is the “official” Linux Bluetooth stack known as BlueZ, which is

incorporated into the Linux 2.4.6+ kernels (http://bluez.sourceforge.net/). BlueZ

provides support for the HCI, LMP, L2CAP layers, but does not appear to directly

provide an interface for RFCOMM. BlueZ is supported by the ARM architecture and in

Page 57: Java Application for Bluetooth

48

particular is available packaged for the Ipaq. It appears to be inferior to the OpenBT

stack in terms of features.

The final consideration is the Affix Bluetooth stack developed by Nokia. This stack has

been tested for the Ipaq and is available pre-compiled It provides support for the HCI,

LMP, L2CAP, SDP and RFCOMM protocols, in addition to providing OBEX support

via the OpenOBEX open source OBEX library. The Affix stack provides libraries to

allow programmers to access HCI and SDP functions and uses a socket based interface

to form RFCOMM connections in contrast to TTY drivers used by OpenBT. Because it

has a more comprehensive feature set than with BlueZ or OpenBT and has been pre-

compiled and known to work on the Ipaq, the Affix stack is the most fitting stack to use

for the project.

3.5.3 Operating System and JVM

Using the Affix Bluetooth stack requires a Linux based operating system. The most

common Linux distribution for the Ipaq, and that which is supported by Compaq, is the

Familiar distribution. The Familiar distribution is based on a Linux distribution

originally started by Compaq themselves (http://familiar.handhelds.org/). It was

developed by Carl Worth and Alexander Guy and included features such as the

BlackBox Window manager and the XFree86 X Windows system. The Familiar

distribution version 5.2 will be used as the operating system for this project.

Selecting the Affix stack automatically means a Linux based JVM must be used. The

Kaffe Virtual Machine is the only JVM for Linux on the Ipaq that provides the AWT

(Abstract Windowing Toolkit) support required by the ME4SE classes. Thus, it will

used for the prototype system.

3.5 Distributed Mobile Services

The experimental application is supported by transportation services supplied by a

combination of a Bluetooth RFCOMM channel and a TCP/IP backbone which provides

the necessary transportation layer for data to be exchanged between the Java client and

the server. The application developer must define the semantics for communication

between the server and the client. For client-server systems, Sommerville [14] suggests

Page 58: Java Application for Bluetooth

49

an application should be broken down into three logical layers as shown in figure 9.

Once the layers of the application are identified, they can be distributed between

computers.

Depending on the distribution of these layers in the system, Sommerville [14] classes

the system as either following a thin-client or fat-client model. In a thin-client model,

the client is only responsible for the presentation layer, and the server does the

application logic and data management. A HTML browser is an example of a thin

client. In contrast, a client under the fat-client system is also responsible for the

application processing, leaving the data management to the server.

The MIDP provides the necessary presentation layer for the application, through a

defined user interface API. Additionally, a MIDP application gives the developer some

degree of control over what fraction of the application logic is processed by the client.

For example, data validation could be performed by the server or by the client. There

are trade offs for moving the amount of application logic performed on the client. As

network latency is usually much longer than the application logic processing time, a

‘fatter’ client tends to be more responsive to the user. Of course, the more application

logic built into the MIDP program, the bigger the size and the longer the initial

download time.

Presentation layer - concerned with user interaction

Application processing layer - concerned with implementing the logic of the application

Data Management Layer - concerned with database operations

Figure 9 – Distributed System Layers [14]

Page 59: Java Application for Bluetooth

50

For the experimental application, it can be assumed that the data management layer will

need to reside on the server. The data management layer will be responsible for the

following duties:

• Storing records of the orders and the menu items in a database

• Querying the database for menu items

• Updating the database with order information

Note that the menu information could be hardwired into the application. This would

result in a more responsive application, because the server would not need to be

queried. However should the menu change it is generally easier the information in the

database than in the application. It is assumed the menu changes quite regularly, so

menu information will be kept on the server.

The following duties of the application layer have been identified as follows:

• Directing the user to input required information

• Validating this information

• Retrieving the menu and presenting it to the user

• Allowing the user to construct an order and submit it.

• Maintaining state information about the user’s order.

Because processing time for most of this logic is significantly less than the network

latency, it is desirable that the application layer duties be assigned to the client. The

next part of the design process is to decide on how data will be sent and retrieved from

the server. The semantics of the communication will be based on a remote procedure

call (RPC) paradigm. Some researchers have challenged this paradigm [16] particularly

for ubiquitous systems. Another alternative could be a messaging based system such as

JMS. However, it seems reasonable though to use it for this application because the

design is based on a client-server architecture that requires a blocking request/reply

exchange of information. A RPC seems an appropriate abstraction for the developer to

use to model this exchange.

There can be two approaches taken to developing a remote procedure call method for

the experimental application. The design could use a method of communication

Page 60: Java Application for Bluetooth

51

between the client and server that is unique to the application. Alternatively, the design

could use standardised middleware. Using a communication method specifically

designed for an application has the advantage that it can be optimised to suit

requirements of the application. This can have great performance benefits in mobile

applications where bandwidth and resources on the client are limited. This approach is

only feasible when there are suitably strong connections between the developer of the

client and the developer of the server. Even if this is the case, the custodian of the

service may wish to provide it to a broad range of devices, from TV sets to mobile

phones. It becomes impractical to devise a communication protocol for each client-

server relationship.

In this instance, the application developer needs some way to deal with the

heterogenous nature of the distributed network. Middleware can be utilised to facilitate

communication between distributed entities and provide a high level of abstraction to

the developer to hide the complexities of the network [27]. Middleware for mobile

systems is large area of research. Mascolo, Capra and Emmerich [27] classify the

different types of features desirable in mobile middleware systems, including location-

awareness, and summarises some of the middleware currently available and under

development.

Middleware is somewhat of an ambiguous term, which is applied to a range of

application layer technologies offering different services. It is beyond the scope of this

project to evaluate all the different types and features of mobile middleware as the

emphasis of this research is directed at Bluetooth/Java systems. The fact that Java client

programs can be downloaded to a common execution environment means that this

research will not be concerned with the need for middleware to provide support over the

range of heterogenous client architectures. For this project, middleware is investigated

with the intent of using it to access services via a RPC on remote servers from

Java/Bluetooth clients. It is assumed that the service is used directly between the

mobile client and server. That is to say, the middleware will be assumed to have no

tiers between the server and client. The tier, from the client’s perspective, could be

considered a service itself anyway.

Obviously, services will vary in their architecture requirements, affecting the suitability

of the middleware chosen. What this section will address is how feasible it is to use

Page 61: Java Application for Bluetooth

52

some of the more common middleware systems, including COBRA, Java RMI and web

services, from a Java MIDP client over a RFCOMM/TCP/IP connection for making

remote procedure calls. This is done with the view of looking to utilise the middleware

for the experimental application.

3.6 Middleware Options

3.6.1 COBRA

The Common Object Request Broker Architecture (CORBA) is a well established open

standard for distributed object computing defined by the Object Management Group

(OMG) [28]. CORBA allows methods on remote objects to be invoke regardless of the

language the objects were written in or what operating system exists on the server. An

Object Request Broker (ORB) exists on both the client and the server to mediate the

communication [28]. COBRA contains many advanced features to facilitate distributed

computing including at once request semantics, fault tolerance and load balancing [28].

A trade off of this is that COBRA requires the ORB at the client end to have a large

footprint [28]. This makes COBRA generally unsuitable for the resource constrained

devices targeted by the MIDP.

3.6.2 Java Remote Method Invocation (RMI)

Java RMI was designed to facilitate distributed computing between Java virtual

machines. This middleware allows clients to dynamically retrieve Java classes from

remote services as required. The client can locate services through an RMI registry, and

the RMI classes can automatically retrieve the classes required to use the service [30].

Because of their size, the Java RMI classes and not included as part of the MIDP API.

In terms of MIDP/Bluetooth devices, this means a gateway is required to accesses RMI

services such as the design documented by Mahmoud [29]. Java RMI also limits the

server process to being implemented in the Java language.

Page 62: Java Application for Bluetooth

53

3.6.3 Web Services

A growing area in distributing computing is concept of web services. Web services are

a set of standards used to provide distributed computing for applications using the

existing technologies for retrieving web pages. They include

• The Simple Object Access Protocol (SOAP)

• The Web Service Description Language (WDSL)

• Universal Description, Discovery, and Integration (UDDI)

[31].

3.6.4 Simple Object Access Protocol

As the name suggests, the simple object access protocol was designed as a simplified

means of making remote procedure calls across the internet. SOAP is gaining much

attention in the field of distributed systems, because it underpins Microsoft’s .NET

architecture. The protocol is primarily intended to be used over HTTP, but can also be

used with SNMP and other application layer protocols. It uses XML for marshalling

objects between server and client and for binding the remote method. The SOAP

standard is maintained by the World Wide Web Consortium and documents the format

of XML messages how they are to be sent over HTTP. One advantage of using SOAP

over HTTP is that it easy for the developer to integrate it into existing network

infrastructure that is designed for allowing clients to retrieve web pages. The developer

does not need to modify the existing network security model to create SOAP

applications.

Another advantage of using SOAP compared to other middleware is that it requires

relatively less resources to process a request and a response. This makes it possible to

use with the MIDP profile, and there are two common packages that can be used to

process SOAP requests and responses. Firstly, there is the open source package kSOAP

(www.ksoap.org) was developed by F. Hunter, Sean McDaniel, Renaud Tognelli and

Mark Sanguinetti. This package totals approximately 40kB in a compressed Jar format.

Alternatively, there is a SOAP package produced by Wingfoot (www.wingfoot.com)

which is available for free use in compiled form and is around 33kB in Jar format.

Page 63: Java Application for Bluetooth

54

3.6.5 Web Service Description Language

WSDL is simply a way of documenting how a web service can be used. It is based in

XML and defines a web services using six elements:

• types - data type definitions

• message - an abstract definition of the data being transmitted.

• portType - a set of abstract operations

• binding - protocol and data format specification for the operations and messages

defined by a particular portType.

• Port - an address for a binding.

• Service - a set of related ports

[32]

3.6.6 Universal Description, Discovery, and Integration (UDDI)

UDDI is essentially a large directory where providers can register web services and

where developers look them up. There are four types of entities associated with UDDI.

A Business Entity describes a business providing web services. A Business Service is a

class of services with a business. The Binding Template and Technology Model entities

are incorporated into the WSDL description of a service. UDDI also defines operations

to create, delete and search for these entities. [31].

3.6.7 Incorporating Web Services into Bluetooth MIDP Applications

Web services would appear to be the most viable popular middleware alternative to use

in an MIDP application, primarily because of the relatively small resources required for

processing on the part of the client. This middleware could be utilised to implement

remote procedure calls for the experimental application. It would provide standardised

way of making the procedure calls over TCP/IP and RFCOMM, using SOAP with

HTTP mapping, and would support different architectures and data representation

between client and server. There does not appear to be any documented research on

using web services from a MIDP client over Bluetooth, so the aims of this project can

be extended to evaluate the effectiveness of such a system. Thus, the RPC

Page 64: Java Application for Bluetooth

55

communication for the experimental application will be implemented using web

services.

Figure 10 illustrates how SOAP will be used over the transport layers of the system.

HTTP will be used to transmit the request/response SOAP XML envelopes and will be

mapped over the TCP/IP and RFCOMM connections. The gateway will be required at

as a type of application proxy and route data from the RFCOMM stream over a TCP/IP

connection. Note that HTTP version 1.1 must be used for this system, because the

gateway needs to identify the server from the host parameter in the HTTP header. Of

the two SOAP APIs available for the MIDP, the Wingfoot package will be used because

it is smaller in size, is more thoroughly documented, and can be more easily adapted to

work over a different transport layer than HTTP/TCP/IP.

3.7 Client Application Design

Obviously keen to foster the success of the Java 2 Micro Edition Platform, Sun

Microsystems provides plenty of support to developers. They publish the “MIDP Style

Guide” (http://java.sun.com/j2me/docs/alt-html/midp-style-guide7/index.html) which

documents recommended practices for developing MIDP applications. This project will

use parts of the style guide a basis to assist in the development process.

HTTP/SOAP Server

RFCOMM to TCP/IP gateway

SOAP API

RFCOMM Transport API

Client Application

Server Application

HTTP HTTP

Figure 10. Using SOAP with TCP/IP/RFCOMM

Page 65: Java Application for Bluetooth

56

The style guide identifies three domains or focuses for the device functionality for

MIDP applications. These are information access and communication, business

functions and entertainment. The experimental application lies within the information

access and communication domain, which is characterised by customers using the

application for a short period of time a structured manner. The style guide suggests the

application should be designed to be to operate in an efficient manner that reflects the

characteristics of this domain. The style guide also documents a general process for

designing the MIDP applications with a focus on the user interface. The first part of

this process involves creating a story of a mock situation which can be used to model

the flow of the user interaction with application. For the experimental application, the

following mock situation is conceived:

I enter the café, find a spare table and take a seat. Noting the long line at the counter, I

decide to beat the rush be ordering through my MIDP device. I discover there is a café

services application available for the wireless server, and download it to my device. I

use the application to view the menu and chose a sandwich. After a while, my sandwich

arrives. Once I finish my meal I decide I need a coffee, so I revisit the application to

submit another request.

The second part of the design process is to design a number of screens from the flow of

the story. A screen is the main abstract component of the MIDP user interface API.

Each screen has associated commands and graphical components that the user can

interact with. There are two levels of abstraction available to developers for creating a

user interface wit the MIDP. High level components include lists and text boxes which

can be placed on screens objects. The drawing of these high level components is the

responsibility of the MIDP implementation and the API to use these components is

designed in such a way to make them portable across and range of devices. The low

level API gives the developer more control over what is displayed on the screen by

providing functions such as drawing shapes. The low level API is generally used for

games and is not required by this application.

In additional to visual components, the user input is also divided into high level and low

level components. In the high level context, the MIDP defines ‘abstract commands’

that the implementation can map to buttons or other user input on the device. Abstract

commands have a label, priority and a type as properties and can be added to a screen.

Page 66: Java Application for Bluetooth

57

The type of a command may take values such as ‘OK’, ‘BACK’ and ‘CANCEL’ which

allows the command to be mapped appropriately by the implementation to input

methods on the device. The low level user input API allows the application developer to

determine such information as specific keys pressed on the device, but again is not

required for this type of device.

Appendix A shows the screens designed for the application and the flow of the

application. The application will change screen will an abstract command is called.

The user is initially presented with the title screen, from which they can choose to view

the menu, view their order or view the status of their flight. The menu into four types

for categories, starters, main courses, deserts and drinks. Selecting a category then

displays a list of meals available under that category. Selecting a meal from this list

displays a price and description of the meal. The user has the option of ordering this

meal, or viewing the rest of the menu. The application is designed to allow users to

browse the menu without committing to an order.

An order is created once in the lifetime of the application by sending the users name and

seat number to the server. The server responds by sending an ‘order number’ to the

client application that uniquely identifies an order in the café. The client application

can then use that number to order items. The user can add and remove items from

their order, and when they are finished they can submit their order to the server. The

user can then still use the application to compile another order of items to submit if they

wish, as in the mock situation. Finally, the user can submit their flight code to the

server to receive an update on the status of their flight. It was originally thought a real

airline company SOAP server such as that used by Continental Airlines

(www.continental.com) could be used to retrieve actual flight times. Unfortunately, an

operational airline SOAP server could not be located. Thus a mock server will be used

to model a real airline server.

Appendix B shows how the program has been designed in a similar fashion to a state

machine. The screens represent the current state of the application as displayed to the

user. The abstract commands act as signals to change between screens and can also

trigger other actions such as adding items to the order.

Page 67: Java Application for Bluetooth

58

Appendix C describes the classes to be used in the application. The classes

RemoteMethods and CLDCTransport are given a particular focus because they relate to

the networking issues underlying this project. The RemoteMethods class provides the

client stub for making SOAP calls to the server. From the design of the screens, three

remote methods are identified that are required by the client:

• Menu viewMenu (void) – fetches the café menu

• int newOrderNumber(String name, int seatNumber) – registers a customer with

the server and returns with a unique order number

• int orderItem(String menuItemName, int orderNumber) – submits an item that

the customer wishes to order.

Note that the actual implementation of the viewMenu procedure differs slightly from

what is described here to allow for more efficient sorting of the menu items into types.

The remoteMethods class maps these methods into SOAP calls using the WingFoot

SOAP package. The WingFoot package makes invoking SOAP calls very easy through

the use of the ‘Call’ class. To invoke a call, an instance of this class is created and the

method name and remote object URI are set using the setMethodName() and

setTargetObjectURI() methods respectively. Parameters can then be added to the

SOAP call with the addParameter(). The call is then invoked using the

invoke(Transport t) method, which accepts an object that provides the transport for the

SOAP envelope. This method returns an object of class Envelope. The returned object

can be then extracted from the envelope object using the getParameter() method and

casting the result to the appropriate Java object..

The CLDC Transport provides a very basic implementation of the HTTP/RFCOMM

transport layer. When this class is invoked by the Wingfoot package, it establishes a

Bluetooth connection with predefined Bluetooth gateway and sends the SOAP envelope

over the RFCOMM channel using HTTP/1.1. Strictly speaking, the application should

discover the gateway device and search for the SOAP gateway service first before

establishing a connection. However, because it is assumed there is only one gateway

device in the café, this is not really necessary. Service discovery is already assumed to

be performed when the application is downloaded.

Page 68: Java Application for Bluetooth

59

3.8 Server Design

The architecture required by the SOAP server is shown in figure 11. The web server

receives the SOAP HTTP request and forwards the XML payload to the SOAP method

binder. The binder parses the XML to determine the remote procedure to call in the

server application and the parameters to use. The server application performs the

application logic required, querying and updating the database containing the café’s

orders and menu. Note other applications could be created to display the information in

the database to Café waiters, but that is outside the scope of this project.

This type of architecture is very common, with many alternatives available for

implementing each entity. The main criteria for selecting technologies to implement the

server are speed of development and reliability. The design of the server, unless it turns

out to be unusually slow, does not heavily impact on the performance and non-

functional properties of the client being evaluated in this research. Thus, a design

should be used that can be developed quickly to provide the necessary functionality

without impacting on the rest of the project. A sufficing decision is made to use a line

of products for the Microsoft Windows XP operating system. This includes Microsoft’s

Internet Information Services (IIS) version 5.1 as the web server, a Visual Basic 6.0

constructed COM object as the server application and a Microsoft Access Database as

the back end database. A product known as 4S4C (http://www.4s4c.com/4s4c/docs/)

developed by Simon Fell, will be used to bind the incoming HTTP SOAP requests to

procedures in the COM object. This product is available as freeware and is easily

installed to work with IIS 5.1.

Web Server

SOAP method binder

Server Application

Database

Figure 11. Server architecture.

Page 69: Java Application for Bluetooth

60

The database is very simple and is constructed from the tables shown in figure 12. Note

the bold font indications primary keys while the arrows indicate foreign keys. This

database is queried and updated from a COM object that implements the remote

methods described in the design of the client. The COM object uses the Microsoft

DAO 3.6 Object Library to query and update tables in the Microsoft Access database

file. This makes the implementation of these methods very straight forward. Once

4S4C is installed, the COM object is registered in the configuration file of the program

as described in (http://www.4s4c.com/4s4c/docs/).

3.8 Design for the client Java Bluetooth interface

In order to use Java for establishing RFCOMM connections to the gateway, an interface

is required between the virtual machine and the Affix Bluetooth Stack. As has been

discussed, the JSR-82 defines an API for using Serial Port Profile with in Java through

the Connector class. An RFCOMM connection to Bluetooth Address btaddr on channel

is established using the open method as follows:

Connector.open(“bt_spp://btaddr:channel);

Table: Items Name Description Type PriceDollars PriceCents

Table: Orders OrderNumber CustomerName SeatNumber

Table: OrderItems OrderNumber ItemName

Table: OrderNumbers HighestOrderNumber

Table: FlightStatus FlightCode Status

Figure 12. Database Schema

Page 70: Java Application for Bluetooth

61

To implement this interface an extra class called ConnectionImpl_btspp must be created

and added to the ME4SE package. Figure 13 shows the methods of this class, which is

instantiated by the Connector class when the ‘bt_spp’ prefix is found in the URL passed

in the open method. The open method of this class is then called to establish a

connection. The design of the ConnectionImpl_btspp is based on source code in the

reference implementation of the CLDC provided by Sun Microsystems. The class is

adapted for the reference implementation’s serial port connection class. Two private

classes are used to create input and output streams for reading from and writing to the

RFCOMM connection. These classes and the ConnectionImpl_btspp class interface to

the Affix stack through the Java Native Interface (JNI). JNI is not normally supported

by the CLDC, but it can be use with Kaffe and the ME4SE classes, which are external

to the application execution environment used for the running the actual MIDP/CLDC

application.

Four native methods, open, close, read and write, are required to use the Affix stack.

These methods are contained in the RFCOMM class as shown in figure 14. The native

methods are contained in a loadable module that uses the Affix stack through a

Berkeley socket interface. An RFCOMM socket is created using the following

function:

socket = socket(PF_AFFIX, SOCK_STREAM, BTPROTO_RFCOMM);

The PF_AFFIX is a new protocol family introduced by the Affix stack. As part of this

connection, a new address structure is defined for making RFCOMM connections as

follows.

Page 71: Java Application for Bluetooth

62

Connector.open(bt_spp:\\address:channel)

public class ConnectionImpl_btspp extends ConnectionImpl implements StreamConnection public void open (String url, int mode, boolean timeouts) throws IOException public InputStream openInputStream () throws IOException public DataInputStream openDataInputStream () throws IOException public OutputStream openOutputStream () throws IOException public DataOutputStream openDataOutputStream () throws IOException public void close () throws IOException

class PrivateInputStream extends InputStream public PrivateOutputStream(ConnectionImpl_btspp parent) throws IOException void ensureOpen() throws IOException synchronized public int write(int b) throws IOException synchronized public int write(byte b[], int off, int len) throws IOException

class PrivateOutputStream extends OutputStream public PrivateInputStream(ConnectionImpl_btspp parent) throws IOException void ensureOpen() throws IOException synchronized public int read() throws IOException synchronized public int read(byte b[], int off, int len) throws IOException public synchronized void close() throws IOException

Figure 13. The Interface for the Bluetooth connection classes

Page 72: Java Application for Bluetooth

63

struct sockaddr_affix {

sa_family_t family;

BD_ADDR bda;

uint16_t port;

BD_ADDR local;

};

The values of ‘bda’ and ‘port’ are the Bluetooth address of the gateway and the channel

number respectively. They can be extracted from the URL passed to the Connector

class and supplied to the native ‘open’ method to connect to the gateway using the

connect function as follows:

connect(socket, sockaddr, addrlen);

The ‘read’ and ‘write’ methods can then easily be mapped to the ‘send’ and ‘recv’

functions used with socket connections.

public class RFCOMM static native int openRFCOMM(String BTAddr, int channel); static native int closeRFCOMM(int handle); static native int readRFCOMM(int handle, byte b[], int offset, int len); static native int writeRFCOMM(int handle, byte b[], int offset, int len); public static int openRFCOMMJava( String BTAddr, int channel) throws IOException public static int closeRFCOMMJava( int handle) throws IOException public static int readRFCOMMJava( int handle, byte b[], int offset, int len) public static int readRFCOMMJava( int handle, byte b[], int offset, int len)

Figure 14. RFCOMM Class.

Page 73: Java Application for Bluetooth

64

3.8 Gateway Design

The design of the gateway for this project is limited to resources available for

development. This project will use a Linux PC with an Ericsson Bluetooth

Development Kit to provide the functionality of the gateway, primarily because of the

availability of these resources.

Though theoretically there should not be a problem between using different Bluetooth

stacks, to try to ensure the compatibility and to leverage from the experience gained

with the client, the Affix stack will also be used with the gateway.

Read the incoming HTTP header into a buffer from standard input.

Determine the server from the ‘Host’ parameter in the HTTP header and form a TCP/IP connection with that host on port 80.

Determine the length of the body from the ‘Content-Length’ field in the HTTP header. Receive the body from standard input and send the header and body to the server

Receive the HTTP header and body response from the service from the server. Write the response to standard output.

Figure 15. The gateway process

Page 74: Java Application for Bluetooth

65

The Affix stack can be used as a Bluetooth server, so that when an incoming RFCOMM

connection is received on a channel, a server application is started with the standard

input and output streams of the process connected to the RFCOMM channel. The

gateway process is shown in figure 15. Note that the process must first determine the

server address using the ‘Host’ parameter in the incoming HTTP header. This process

will be implemented using ‘C’ code and compiled into an executable binary file.

Page 75: Java Application for Bluetooth

66

Part 4 – Implementation

4.1 Overview

This section documents the results of implementing the design for the application. It

describes any problems that occurred and any changes made to the system design.

4.2 Implementation of the test Client MIDP Application and SOAP

server.

The code for the MIDP application is shown in appendix D. This code implements the

design for the client application described in the previous section. The code was

complied using the Sun Microsystems Wireless Toolkit Version 1.04_01. It was noted

that the latest version of the toolkit was required in order to use the Wingfoot package.

The user interface for the application was tested using the MIDP device emulator, as

shown in figure 16. The user interface worked satisfactorily, and there was no changes

made to the conceptual design of the screens and the flow of the application.

The design for the SOAP server system was implemented on a remote computer, with

the Visual Basic code for the server application shown in appendix E. The server was

Figure 16. The application running in the emulator.

Page 76: Java Application for Bluetooth

67

tested with the MIDP client running on the emulator by using direct TCP/IP socket

connections. From testing the following results about the performance of the system

were obtained:

• One situation that was not anticipated in designing the client was that the IIS

server returns a HTTP header with a response code 100, indicating that the

request was received and being processed. The design of the CLDCTransport

class required slight modifications from the original design to remove the first

response header. This also had ramifications for the gateway design, and similar

code was required to wait for the second HTTP response from the server.

• The remote methods were mostly functionally sound and generally produced the

correct results. For some unknown reason, the 4S4C software returned an extra

null menu item after the view menu function was called. This problem could

easily be worked around.

• In terms of speed, there is some delay of approximately 3 seconds in processing

the SOAP response for the ‘viewMenu’ remote procedure call.

• Some changes to the server and client application were trialled to increase speed

of submitting an order by sending multiple items in an order call to the server.

However, the 4S4C software did not pass arrays effectively to the server

application, so the attempt was unsuccessful. A possible solution may have

been to send a delimited string of the order item names, but this would defeat the

purpose of using the SOAP protocol.

In summary, there were no major design changes to server or client at this stage and the

remote procedures worked effectively over a socket connection.

4.3 Ipaq Setup

In contrast to the previous implementation stage, the results of implementing the

application on the Ipaq were much less encouraging. A number of problems were

encountered that resulted in substantial changes to the original design.

The installation of the necessary software on the Ipaq was a slow but generally

successful process. Installing the Familiar distribution, which also required installing a

new boot loader, was a slow process that was at times poorly documented by

Page 77: Java Application for Bluetooth

68

www.handhelds.org, but was without any major problems. The Familiar distribution

includes a package management program called ‘ipkg’ which made installing the Kaffe

JVM and the Affix stack very straight forward.

The combination of the ME4SE classes and the Kaffe JVM was tested with a sample

MIDP application and two issues became apparent. Firstly, the Kaffe JVM does not

work with compressed JAR files. As a result, the size of an application stored in a JAR

file would increases significantly, which would impact on the time taken to download

the application to the Ipaq. Secondly, the virtual machine is slow and takes around

seven seconds to load the application. This is an obviously undesirable delay for the

user to be subjected to

4.4 Implementing the gateway

The gateway proved to be very problematic to implement. Firstly, the Affix stack took

much longer than expected to compile for the Redhat Linux 7.2 system, because of the

number of libraries that had to be found and installed beforehand. Secondly, it was not

clear how custom server processes were to be configured with stack as the

documentation for the stack was lacking in detail in this area. Finally, once installed the

Affix stack could not detect the Ericsson Bluetooth Development Kit despite Nokia’s

claims that the stack was compatible with this hardware. The authors of the Affix stack

were contacted over this problem, but could not offer a solution that fixed the problem.

Due to the problems with the Affix stack, it was decided to use the OpenBT Bluetooth

stack instead. The OpenBT stack was compiled for the system and was successfully

tested to prove that a RFCOMM connection could be formed with the Affix stack on the

Ipaq. As a consequence of changing Bluetooth stacks, some modifications were

required to the design of the gateway. Firstly, instead of reading and writing to the

standard input and output streams, the server process must use the device ‘/dev/ttyBT0’

instead. Secondly, the server process is no longer activated and must be listening for a

HTTP request on the device at all times. Thirdly, some initiation of the Bluetooth

driver is required before RFCOMM connections can be received. This is performed by

using code based from Bray [3] to create a simple application which then calls the

gateway program. The code for the gateway is shown in appendix F.

Page 78: Java Application for Bluetooth

69

4.5 Providing the Java interface to the Affix Bluetooth Stack

This part of the implementation process was the most time consuming and caused the

most problems. The following steps describe the process undertaken to achieve the

required functionality with the interface.

1) Initially a simple experimental application was created to test using the Affix

socket interface. This application was cross-compiled for the Ipaq using the arm

cross-compilation environment provided by Johan Hedberg at

http://affix.sourceforge.net/ipaq.shtml. This application was successful in

demonstrating that a RFCOMM connection could be established with the

OpenBT stack on the gateway and data sent over that connection.

2) The original interface design was implemented and code is shown in appendix

G. The native methods for the Java Bluetooth interface were implemented as a

JNI library and a simple experimental Java program was created to test the

methods. Testing showed that the Java application was unreliable in forming

and sending information over a RFCOMM connection. The native method for

writing to the connection would report that the socket was disconnected. After

extensive testing, it was determined that the native methods worked perfectly

when called by native code, but would be unreliable when called by the Kaffe

VM. It was therefore inferred that there was some sort of resource conflict

between the Kaffe VM and the Affix Stack.

3) An alternative design was conceived that did not use the JNI. Instead, a native

application was written that is executed using the Process class. The application

accepts a Bluetooth address and channel number on start up and forms an

RFCOMM connection. The process then performs a fork and the child process

reads data from the socket and writes this data to the standard output stream.

The parent process reads data from the standard input stream and writes this data

to the socket. The native application is started by the open method of the

RFCOMM class which is called by the ConnectionImpl_btspp class. Instead of

the native methods of the RFCOMM class, the standard input and output streams

associated with native application are used for reading from and writing to the

connection. This code is shown in appendix H.

Page 79: Java Application for Bluetooth

70

This new design rectified the problem encountered with using the JNI. However, the

new design does not allow for timeouts when reading from the connection, which

affects the reliability and robustness of the application. Additionally, if the main Java

process encounters an exception an exits unexpectedly, it can leave the other processes

running in the background.

4.6 Implementation and evaluation of the total system

The final stage of the implementation process involved testing the MIDP application

running on the Ipaq. The results of this stage are summarised as follows:

• Because the OpenBT stack is based around serial drivers, the carriage return

characters that were being sent by the MIDP application as part of HTTP

requests were being interpreted as control characters. This problem was fixed

by changing the settings of the serial device used by the gateway with the

‘termios’ command.

• There is a bug in the ME4SE classes such that the MIDP application does not

work correctly unless a canvas screen is initially used. This is easily worked

around though.

• Because Bluetooth hardware in the Ipaq is accessed through a UART, the baud

rate for RFCOMM connection is capped at 115200. Even worse, the Ericsson

kit, which is also accessed using a serial connection, is set initially to use a baud

rate of 57600. Attempts to change the serial connection to a higher baud rate as

documented in (Bluetooth Developers Guide) did not work. Thus the Bluetooth

connection is transferring data much slower than the technology is capable of.

• The slow processing of the Kaffe JVM, the slow Bluetooth connection and the

processing in the XML parsing required as part of the SOAP package combine

to make the start up time of the application to be between 10 and 20 seconds.

Despite the problems, the application was successfully implemented with the

functionality to view and order items from the menu, in addition to checking a flight’s

status from the server.

Page 80: Java Application for Bluetooth

71

Part 5 – Evaluation 5.1 Overview This section will complete the following objectives:

- Evaluate the outcomes of the project against the original aims

- Evaluate the final system based on the non-functional criteria

- Draw conclusions about the effectiveness of the design

- Make recommendations towards further work based on this research

5.2 Outcomes of the project

In reviewing the outcomes of the project, the aims of project are reconsidered.

• To analyse the features and limitations of Bluetooth and Java technology and

investigate what scenarios could benefit from a wireless application

implemented using this combination.

As part of the analysis stage of this project, Bluetooth and Java technologies were

examined and it was concluded that they would best serve a location based application

that could be downloaded onto a mobile information device. A number of potential

markets for this type of application were identified and it was decided that an ‘Airport

Café’ application would be developed.

• To define a specification for an experimental Bluetooth/Java application and

design a solution to this specification using available technologies. The solution

will be a wireless system that provides a service of value to the end user via a

graphical interface.

The functionality that the experimental application should have was identified.

Assumptions were made about the application’s environment and a design for the

application system was conceived. Alternatives for various system components were

Page 81: Java Application for Bluetooth

72

evaluated, including middleware for the application. The design of software

components and their integration was also carried out.

• Implement the prototype solution and evaluate the value of the Bluetooth/Java

system from the perspective of the user in terms of the added convenience from

traditional methods of using the service.

A functional application was implemented. The results of the implementation,

including changes to the original design have been noted. The final stage of the project

involves evaluating the design and recommended further work directions in this area.

5.3 Evaluation of the final system design

As part of the analysis stage of this project, a set of criteria was established to evaluate

the value of the application.

5.3.1 Added convenience

Unfortunately, due to the slow start up time of the application, the café would have to

be very busy for ordering through the application to be quicker than ordering manually.

That aside, the application does offer the functionality to place an order and view a

flight’s status without the user leaving their seat, which can be seen as added

convenience. A user may finder the application tedious to use however if they have a

longer order to submit.

5.3.2 Speed

The application performs poorly in this area, especially during start up which may take

between 10 and 20 seconds. The Kaffe JVM is very slow, and the addition of the

ME4SE classes to simulate a MIDP environment does not help this cause. The

processing time required to extract the menu from the SOAP response also contributes

to the large delay. The speed of the application is most likely to be unacceptable to the

user.

Page 82: Java Application for Bluetooth

73

5.3.3 User Interface

It is difficult to evaluate how effective the user interface is without actually testing it

with subjects. No major problems are apparent though. One observation is that in

trying to achieve portability across a range of devices, the MIDP user interface appears

bland on devices such as the Ipaq that are capable of producing much richer graphics.

5.3.4 Security

The level of security required for this application is arguable. As it involves general

information browsing, one might argue that there is no need for encryption or

authorisation. Others may argue that confidentiality of what the person is ordering or

viewing must be maintained. No security mechanisms were implemented as part of this

research.

5.3.5 Reliability

This is another area in which the application is let down. The problem with using the

JNI meant no time out could be implemented on reading from the connection. Thus the

application would stall if a HTTP response was not received. This could possibly be

resolved using threads in the program, but this would consume more processor

resources and slow the program down even further. The gateway was designed to leave

the uses of reliability to the client and timeout and return to its initial state if a response

was not received. Both the OpenBT and Affix Bluetooth stacks had occasional

problems forming connections for no apparent reason and the OpenBT stack would

even lock the kernel at times. In general, the reliability of the application would need to

be improved to make it an acceptable product for consumers to use.

5.4 Design Conclusions

As a general conclusion, it would seem that Java 2 Micro Edition and Bluetooth

technologies are still too much in their infancy stages for application developers to write

any compelling applications using them. In refection, the scope of the project was

probably set too broadly given the limited development in Java and Bluetooth on the

Page 83: Java Application for Bluetooth

74

Ipaq. As supported by the results of the experimental application, developers are not

yet equipped with the resources to develop end-product quality Java/Bluetooth

applications for the Ipaq, nor any other device for that matter. In fact a Java 2 Micro

Edition platform that supports a graphical user interface is not even readily available for

the Ipaq. Taking into account the politics of software companies, this may be because

main operating system for the Ipaq, Pocket PC 2002, is a product of rival Microsoft and

Sun are interested in finding there own domains. Instead, a range of outdated virtual

machines are available, hindering the portability of Java applications.

Additionally, with the technology sector still apparently absorbed the complexity of the

Bluetooth specification and the infancy of the Bluetooth Java API, there are few

resources available for using Bluetooth from a Java environment. A ubiquitous

Java/Bluetooth application environment is very far from reality.

This project has developed a design for a system that shows how a program executing in

a MIDP/CLDC/JSR-82 conforming environment can be used to access wireless services

in an example environment. As the resources for the development were limited and

generally experimental, only a prototype system could be implemented that proved the

functionality of the system, but was not of commercial value. Many optimisations of

the system are required to make it faster and more reliable.

The project also demonstrated how web services can be accessed from a Bluetooth

connection using a Java MIDP application. However, the time consumed in processing

the service responses makes the value of using web services in this environment

questionable. Again, a faster execution environment is required for the application of

this technology to have any value to the user

5.5 Future Recommendations

No further work is suggested directly on the system developed in this project. Instead,

it is suggest research efforts be concentrated on developing a more effective

Java/Bluetooth environment for application development. The Java Virtual Machine

should be optimised for the processor and operating system of the device while the

interface of the Bluetooth stack should be designed with the intent of integrating it with

Java. There are a couple of ways of speeding up the execution of the byte codes in a

Page 84: Java Application for Bluetooth

75

Java Virtual Machine that could result in a faster and more responsive application for

the user. It should be remembered however, that interpreted code will never run as

quickly as native code. Firstly, the implementation of JVM can be optimised, such as

the Hot Spot KVM from Sun Microsystems. Secondly, a JVM can be implemented in

hardware to provide faster execution.

Further research should also be directed at how a user might search for services and

dynamically download Java applications to a Bluetooth device. One possibility is to use

the Bluetooth Service Discovery Profile to discover services. As defined in the

Bluetooth specifications, a service may list the URL of a client application to use the

service. The user could then download the application onto their device. A more likely

scenario in the future is that a technology such as JINI will be used to allow for dynamic

services registration and discovery. JINI is currently too large however to be used with

most embedded devices.

Page 85: Java Application for Bluetooth

76

Bibliography

[1] BlueBoard LLC. ‘Why J2ME’. http://www.blueboard.comJune. 2002. Last visited

October 15 2002.

[2] Bluetooth Special Interest Group. ‘Specification of the Bluetooth System version

1.1’. http://www.bluetooth.com. 2001. Last visited October 15 2002.

[3] Bray, J. 2002. Bluetooth application developer’s guide : the short range interconnect

solution. Rockland: Syngress Media.

[4] Hashman, S. & Knudsen, S. ‘The Application of Jini Technology to Enhance the

Delivery of Mobile Services’. http://www.microjava.com/articles/PsiNapticMIDs.pdf.

June 2002. Last visited October 15 2002.

[5] JSR Expert Group 82. ‘Java API for Wireless Bluetooth Technology’.

http://jcp.org/jsr/detail/82.jsp. 2002. Last visited October 15 2002.

[6] Kaminsky, A. ‘Infrastructure for Distributed Applications

in Ad Hoc Networks of Small Mobile Wireless Devices’.

www.cs.rit.edu/~anhinga/publications/ AnhingaPaper20010522.pdf. May 2001. Last

visited October 3 2002.

[7] Kansal, A. ‘Bluetooth Tutorial’.

www.ee.iitb.ernet.in/uma/~aman/bluetooth/tut3.html. 2000. Last visited October 15

2002.

[8] Mattern, F. & Sturm, P. ‘From Distributed Systems to Ubiquitous Computing - The

State of the Art, Trends, and Prospects of Future Networked Systems’.

http://citeseer.nj.nec.com/507476.html. June, 2000. Last visited October 15 2002.

Page 86: Java Application for Bluetooth

77

[9] Millar, M. 2001. Discovering Bluetooth. Alameda: SYBEX

[10] Miller, B. & Bisdikian, C. 2001. Bluetooth Revealed. Upper Saddle River: Prentice

Hall

[11] Muller, N. 2001. Bluetooth Demystified. New York: McGraw-Hill

[12] P. K. Kannan, P., Chang, A & Whinston, B. ‘Wireless Commerce: Marketing

Issues and Possibilities’. www.hicss.hawaii.edu/HICSS_34/PDFs/ST1MC03.pdf.

January 2001. Last visited September 9 2002.

[13] Thornber, V., Wilson, A. & Wood, G. ‘PDA’s - who needs them?’.

http://www.dcs.napier.ac.uk/~mm/socbytes/jun2001/Jun2001_5.htm. June, 2001. Last

visited September 9 2002.

[14] Sommerville, I. 2001. Software Engineering Harlow: Pearson Educational

[15] Sun Microsystems, Inc. ‘J2ME TM Technology for Creating Mobile Devices’.

http://java.sun.com. 2000. Last visited September 9 2002.

[16] Greaves, J. ‘Communication Primitives for Ubiquitous Systems or RPC

Considered Harmful’. www.cag.lcs.mit.edu/~umar/publications/RPC.pdf. 2002. Last

visited September 9 2002.

[17] Sun Microsystems, Inc. ‘BluetoothTM Developers and Implementers Can Succeed

with JavaTM Specification Request (JSR) 82’. 2002. Last visited September 9 2002.

[18] Sun Microsystems, Inc. ‘Connected, Limited Device Configuration, Specification

Version 1.0.a’ http://java.sun.com/. May 2000. Last visited September 9 2002.

[19] Sun Microsystems, Inc. ‘Mobile Information Device

Page 87: Java Application for Bluetooth

78

Profile (JSR-37) JCP Specification Java 2 Platform, Micro Edition, 1.0a’.

http://java.sun.com/. May 2000. Last visited September 9 2002.

[20] Zucotto. ‘WHITEboard SDK, Bluetooth Edition: Developer’s Reference’.

http://www.zucotto.com/ April 2002. Last visited September 9 2002.

[21] Sun Microsystems, Inc. ‘Applications for Mobile Information Devices’.

http://java.sun.com Last visited September 9 2002.

[22] Vainio, J. ‘Bluetooth Security’ http://www.niksula.cs.hut.fi/~jiitv/bluesec.html

May 2000. Last visited September 9 2002.

[23] Varshney, U. Vetter, R.’A Framework for the Emerging Mobile Commerce

Applications’. www.hicss.hawaii.edu/HICSS_34/PDFs/ST1MC02.pdf January 2001.

Last visited September 9 2002.

[24] McCabe, K. ‘TIME FOR A BREW’.

http://www.rococosoft.com/downloads/pdf/Timeforabrew.pdf. 2001. Last visited

September 9 2002.

[25] Surdu, J., Alford, K., Yu, G., Herrington, W. & Maranich, C. ‘Platform

Independent Tactical Data Entry Devices’.

www.stsc.hill.af.mil/CrossTalk/2002/aug/websites.pdf.August 2002. Last visited

September 9 2002.

[26] White, J. & Hemphill, D. 2002. Java 2 Micro Edition. Greenwich: Manning.

[27] Mascolo, C., Capra, L. & Emmerich, W. ‘Mobile Computing Middleware’.

www.cwc.nus.edu.sg/mwcn2002/ntw02.pdf. 2002. Last visited September 9 2002.

[28] Aniruddha Gokhale, A., Arnaud, K. & Sahuguet, B. ‘Reinventing the Wheel?

CORBA vs. Web Services’. www.isis.vanderbilt.edu/~gokhale/PDF/WWW2002.pdf.

2002. Last visited September 9 2002.

Page 88: Java Application for Bluetooth

79

[29] Mahmoud, Q. ‘Advanced MIDP Networking, Accessing Using Sockets and RMI

from MIDP-enabled Devices’. http://wireless.java.sun.com/midp/articles/socketRMI/.

January 2002. Last visited September 9 2002.

[30] Reilly, D. ‘Introduction to Java RMI’.

http://www.javacoffeebreak.com/articles/javarmi/javarmi.html. June 2001. Last visited

September 9 2002.

[31] Ryman, A. ‘Understanding Web Services’.

http://www7.software.ibm.com/vad.nsf/Data/Document4362?OpenDocument&p=1&B

CT. December 2000. Last visited September 9 2002.

[32] Chinnici, R., Gudgin, M., Moreau, J. & Weerawarana, S. ‘Web Services

Description Language (WSDL) Version 1.2 W3C Working Draft 9 July 2002’.

http://www.w3.org/TR/wsdl12/. July 2002. Last visited September 9 2002.

[33] Cousins, K. Varshney, U. ‘A product location framework for mobile commerce

environment Authors’. http://doi.acm.org/10.1145/381461.381469. 2001. Last visited

September 9 2002.

Page 89: Java Application for Bluetooth

80

Appendix A – MIDP Application Screens

If an order number has been received then go to the ‘Title’ screen.

Welcome

Select an option - View Menu - View my Order - Check my flight times

EXIT OK

Menu

- Starters - Main Courses - Deserts - Drinks

BACK VIEW

Starters

- Garlic Bread - Chips

BACK OK

Garlic Bread: $4.50 Five Pieces

BACK ORDER

Title Screen Menu Screen

Type Screen Item Screen

If an order number has not been received then go to ‘Request Name’ screen

If an order number has been received then go to the ‘My Order’ screen.

Page 90: Java Application for Bluetooth

81

My Order

Select an option - View order - Add item - Remove item - Submit order

BACK OK

Total Order: $4.50

Garlic Bread

BACK REMOVE

Please enter your name

Name

BACK OK

Please enter your seat number

Seat Number

BACK OK

To Title Screen

Request Seat Screen Request Name Screen

To ‘Menu’ Screen

My Order Screen View Order Screen

Page 91: Java Application for Bluetooth

82

Please enter your flight code

Flight Code

BACK OK To ‘Title’ screen

To ‘Title’ screen Flight Times Screen

Page 92: Java Application for Bluetooth

83

Appendix B – MIDP Application Classes

Class Description

Cafe The main controlling class that extends the MIDlet class. This class

contains all the screens, screen components and commands.

Methods (excluding those inherited):

void changeList (List listToChange, Vector vectorToInsert) – replaces

the values in a list with those in the Vector

void orderItemScreenItem ()- orders the item currently selected in the

item screen.

CLDCTransport This class implements the Transport interface, used by the Wingfoot

Soap package, to make SOAP remote procedure calls over a transport

layer.

Methods (excluding those inherited):

public byte[] call(byte[] payload) throws SOAPException, IOException

- This method is invoked by the Wingfoot package to send a SOAP

envelope over an RFCOMM Bluetooth connection. The Bluetooth

connection is formed using the JSR-82 interface.

MyOrder This class is used for forming objects representing a customers order.

Each order has an associated customer first name, table number, order

number and order of menu items.

Methods:

public MyOrder (String pFirstName, int pTableNumber, int

pOrderNumber)

- constructor for the MyOrder object

Page 93: Java Application for Bluetooth

84

public void addItem (MenuItem pItem)

- adds an item to the order

public void removeItem (MenuItem pItem)

- removes an item from the order

public void submitOrder ()

- send the order to the server

public Vector getOrder()

- get the order

public void refreshOrder()

- clear the order

public String getTotalPriceAsString()

- return the total price of the order as a String

RemoteMethods This class provides the network stub for calling remote procedures.

Methods:

public static int newOrderNumber(String customerName, int

seatNumber)

- creates a new order on the server and returns an order number

public static int orderItem(int orderNumber, String itemName)

- orders an item from the menu

public static int viewMenu (Vector pStarters, Vector pMains, Vector

Page 94: Java Application for Bluetooth

85

pDeserts, Vector pDrinks)

- retrieves the menu from the server

MenuItem This class is used for forming menu item objects. Each menu item has an

associated name, description, type, cost in dollars, cost in cents (float

types are not supported).

Methods:

public MenuItem (String pName, String pDescription, int pPriceDollars,

int pPriceCents)

- Constructor method for a Menu Item.

Page 95: Java Application for Bluetooth

86

Appendix C – MIDP Application Command Actions

Note the ‘BACK’ command has been excluded from this table. The back command

always results in a screen change which is shown in Appendix A.

Screen Command Action

OK - If the ‘view menu’ item is selected from the

list then change to the Type Screen.

- If the ‘view my order’ item is selected then

determine whether if an order has been

established. If so, go to the ‘My Order’

screen. If not, go to the ‘Request Name’

screen.

- If the ‘Check my flight time’ item is selected

from the list then go to the Flight Times

screen.

Title

EXIT

- Exit the application

Menu OK - Go to the ‘Type’ screen. Load the list in the type

screen with menu items of the type selected from the

list in the menu screen.

Type OK - Go to the ‘Item’ screen. Display the name, price

and description of the item selected in from the list in

the ‘Type’ screen.

Item ORDER - If an order has been created, then add the

item to the order and display the ‘Added

Item’ alert with the name of the item added.

Go to the ‘My Order’ screen.

- If not, go to the ‘Request Name’ screen.

Request

Name

OK - Go to the ‘Request Seat’ screen.

Page 96: Java Application for Bluetooth

87

Request Seat OK - Send the name and seat number details to the server

and receive an order number. If an item was ordered,

then add the item to the order and display the ‘Added

Item’ alert with the name of the item added. Go to

the ‘My Order’ screen.

My Order OK - If the ‘View Order’ item is selected from the

list, then load the ‘View Order’ screen,

setting the list in this screen to display the

menu items currently in the user’s order.

- If the ‘Add Item’ item is selected from the

list, then go to the ‘Menu Screen’.

- If the ‘Remove Item’ item is selected from

the list, then load the ‘View Order’ screen,

setting the list in this screen to display the

menu items currently in the user’s order.

- If the ‘Submit Order’ item is selected then

submit the order to the server. Display the

‘Submit Order’ alert confirming the order has

been sent to the server. Return to the title

screen.

Flight Times OK - Query the serve for the status string of the

flight. Display the status string in the ‘Flight

status’ alert. Return to the ‘Title Screen’.

View Order REMOVE - If no items are available, the set the text of

the ‘Remove Item’ alert to inform the user no

items are available. Return to the ‘My Order’

screen.

- Otherwise, remove the selected item from the

order. Set the text of the ‘Remove Item’ alert

to inform the user the item was removed.

Return to the ‘My Order’ screen.

Page 97: Java Application for Bluetooth

88

Appendix D – MIDP Application Source Code

Class: RemoteMethods.java

/* * RemoteMethods.java - Class for calling remote server methods * Author: Benjamin Williams * Last modified: 5/10/2002 */ import com.wingfoot.soap.encoding.*; import com.wingfoot.soap.*; import java.util.*; import java.io.*; import javax.microedition.io.*; public class RemoteMethods { /*

Create a new order number and store the customer name and seat number on the server

*/ public static int newOrderNumber(String customerName, int seatNumber)

{ // Create the SOAP envelope Integer answer = new Integer(0); Call theCall = new Call(); TypeMappingRegistry registry = new TypeMappingRegistry(); Envelope requestEnvelope = new Envelope(); // make the SOAP call try { theCall.setMethodName("newOrderNumber"); theCall.setTargetObjectURI("http://mark/menu"); theCall.addParameter("customerName", customerName); theCall.addParameter("customerSeat",

new Integer(seatNumber)); CLDCTransport transport = new CLDCTransport( "http://mark/ssss4c/soap.asp");

answer = (Integer) theCall.invoke(transport).getParameter(0);

} catch ( Exception e)

{ System.out.println( e.toString() ); System.exit( 0 ); } // return the order number return answer.intValue()

Page 98: Java Application for Bluetooth

89

} // submit an order for an item on the reomte server

public static int orderItem(int orderNumber, String itemName)throws Exception

{ // create the SOAP envelope Integer answer = new Integer(0); Integer orderNumberObject = new Integer(orderNumber); Call theCall = new Call(); TypeMappingRegistry registry = new TypeMappingRegistry(); Envelope requestEnvelope = new Envelope(); theCall.setMethodName("orderItem"); theCall.setTargetObjectURI("http://mark/menu"); theCall.addParameter("orderNumber", orderNumberObject); theCall.addParameter("itemName", itemName); CLDCTransport transport = new CLDCTransport( "http://mark/ssss4c/soap.asp"); // make the SOAP call try {

answer = (Integer) theCall.invoke(transport).getParameter(0);

} catch ( SOAPException e) { System.out.println( e.toString() ); System.exit( 0 ); } return answer.intValue(); } // retrieve the menu from the server public static int viewMenu ( Vector pStarters, Vector pMains, Vector pDeserts, Vector pDrinks )throws IOException { UntypedObject answer; UntypedObject menuList; Object [] menuItemArray; Object [] menuItemList; int count; MenuItem theMenuItem; // Create the soap envelope Call theCall = new Call(); TypeMappingRegistry registry = new TypeMappingRegistry();

Page 99: Java Application for Bluetooth

90

Envelope requestEnvelope = new Envelope(); theCall.setMethodName("viewMenu"); theCall.setTargetObjectURI("http://mark/menu"); CLDCTransport transport = new CLDCTransport( "http://mark/ssss4c/soap.asp"); // Make the SOAP call try {

answer = (UntypedObject) theCall.invoke(transport).getParameter(0); menuItemArray = (Object []) answer.getPropertyValue(0);

/* * Retrieve the menu from the response SOAP envelope */

for (count = 0; count < (menuItemArray.length - 1); count++)

{ menuList = (UntypedObject) menuItemArray[count]; String mealType = (String) (menuList.getPropertyValue(2));

theMenuItem = new MenuItem ( (String) (menuList.getPropertyValue(0)), (String) (menuList.getPropertyValue(1)),

((Integer) (menuList.getPropertyValue(4))).intValue(), ((Integer) (menuList.getPropertyValue(3))). intValue()

); if (mealType.equals("STARTER")) { pStarters.addElement(theMenuItem); } if (mealType.equals("MAIN")) { pMains.addElement(theMenuItem); } if (mealType.equals("DESERT")) { pDeserts.addElement(theMenuItem); } if (mealType.equals("DRINK")) { pDrinks.addElement(theMenuItem); } } } catch (Exception e)

Page 100: Java Application for Bluetooth

91

{ System.out.println( "view menu" + e.toString() ); System.exit( 0 ); } return 0; } // Get a string reporting on the flight status from the server public static String getFlightStatus(String flightCode) { // create the SOAP request envelope String answer; Call theCall = new Call(); TypeMappingRegistry registry = new TypeMappingRegistry(); Envelope requestEnvelope = new Envelope(); // make the SOAP call try { theCall.setMethodName("getFlightStatus"); theCall.setTargetObjectURI("http://mark/menu"); theCall.addParameter("flightCode", flightCode); CLDCTransport transport = new CLDCTransport( "http://mark/ssss4c/soap.asp");

answer = (String) theCall.invoke(transport).getParameter(0);

} catch ( Exception e) { System.out.println( e.toString() ); System.exit( 0 ); } return answer; } }

Class: Class: RemoteMethods.java

/* * Cafe.java - Main midlet * Author: Benjamin Williams * Last modified: 5/10/2002 */ import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import java.util.*; public class Cafe extends MIDlet implements CommandListener {

Page 101: Java Application for Bluetooth

92

/* Define screens */ private Form titleScreen; private Form getFlightCodeScreen; private List menuScreen; private List typeScreen; private Form itemScreen; private Form requestNameScreen; private Form requestSeatScreen; private List myOrderScreen; private List viewOrderScreen; private Alert addedItem; private Alert removedItem; private Alert invalidData; private Alert orderComplete; private Alert flightTime; private MyCanvas canvas; /* Define commands */ private Command OKCommand = new Command( "OK", Command.OK, 1 ); private Command orderCommand =

new Command( "Order", Command.OK, 1 ); private Command backCommand =

new Command( "Back", Command.BACK, 2 ); private Command exitCommand =

new Command( "Exit", Command.EXIT, 2 ); private Command removeCommand =

new Command( "Remove", Command.OK, 1 ); /* Define form components */ private ChoiceGroup titleChoices =

new ChoiceGroup ("Select an option", Choice.EXCLUSIVE); private final int viewMenuIndex = 0; private final int viewflightIndex = 2; private StringItem itemDescription = new StringItem("", ""); private TextField nameField =

new TextField("Name", null , 15, 0); private TextField seatField =

new TextField("Seat Number", null , 15, 0); private TextField flightCodeField = new TextField( "Flight Code", null , 15, 0); /* Menu Information */ private final String[] menuItemTypes = { "Starters", "Main Courses", "Deserts", "Drinks" }; private final String[] myOrderOptions = { "View", "Add Item", "Remove Item", "Submit Order"

Page 102: Java Application for Bluetooth

93

}; private Vector startersMenu = new Vector(); private Vector mainCoursesMenu = new Vector(); private Vector desertsMenu = new Vector(); private Vector drinksMenu = new Vector(); /* Information relating to screens */ private Vector typeScreenMenu; private MenuItem itemScreenItem; /* Information stored about user */ private MyOrder myOrderInstance; /* MIDlet constructor */ public Cafe() { initApp(); } /* start application */ public void startApp() { int count; int count2; Display.getDisplay(this).setCurrent( canvas ); Display.getDisplay(this).setCurrent(titleScreen); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} /* Determine the command and take action */ public void commandAction(Command c, Displayable s) { String commandLabel = c.getLabel(); if (commandLabel.equals("OK")) { if (s.equals(titleScreen)) { // Title choices are either view menu, view my order // or check flight times

if (titleChoices.getSelectedIndex() == viewMenuIndex)

{ Display.getDisplay(this).

setCurrent(menuScreen); } else

if (titleChoices.getSelectedIndex() == viewflightIndex)

{ Display.getDisplay(this)

.setCurrent(getFlightCodeScreen); }

Page 103: Java Application for Bluetooth

94

else { if (myOrderInstance == null) { Display.getDisplay(this).

setCurrent(requestNameScreen); } else { Display.getDisplay(this)

.setCurrent(myOrderScreen); } } } else if (s.equals(getFlightCodeScreen)) {

flightTime.setString(RemoteMethods. getFlightStatus(flightCodeField.getString())); Display.getDisplay(this). setCurrent(flightTime,titleScreen);

} else if (s.equals(menuScreen)) { switch (menuScreen.getSelectedIndex()) { case 0: changeList(typeScreen, startersMenu); typeScreen.setTitle("Starters"); typeScreenMenu = startersMenu; break; case 1: changeList(typeScreen, mainCoursesMenu); typeScreen.setTitle("Main Courses"); typeScreenMenu = mainCoursesMenu; break; case 2: changeList(typeScreen, desertsMenu); typeScreen.setTitle("Deserts"); typeScreenMenu = desertsMenu; break; case 3: changeList(typeScreen, drinksMenu); typeScreen.setTitle("Drinks"); typeScreenMenu = drinksMenu; break; } Display.getDisplay(this).setCurrent(typeScreen); } else if (s.equals(typeScreen)) { int selectedIndex = typeScreen.getSelectedIndex();

MenuItem selectedItem = (MenuItem) typeScreenMenu.elementAt(selectedIndex);

Page 104: Java Application for Bluetooth

95

if (selectedItem.priceCents < 10) { itemScreen.setTitle(selectedItem.name

+ ": $" + selectedItem.priceDollars + ".0" + selectedItem.priceCents);

} else {

itemScreen.setTitle(selectedItem.name + ": $" + selectedItem.priceDollars + "." + selectedItem.priceCents);

} itemDescription.setText(selectedItem.description); Display.getDisplay(this).setCurrent(itemScreen); itemScreenItem = selectedItem; } else if (s.equals(requestNameScreen)) { Display.getDisplay(this).setCurrent(requestSeatScreen); } else if (s.equals(requestSeatScreen)) { try { Integer.parseInt(seatField.getString()); } catch (NumberFormatException e) {

invalidData.setString("Please enter a valid seat number!");

Display.getDisplay(this). setCurrent(invalidData, requestSeatScreen);

} /* Fetch the information to create myOrder */ myOrderInstance = new MyOrder ( nameField.getString(), Integer.parseInt(seatField.getString()), RemoteMethods.

newOrderNumber(nameField.getString(), Integer.parseInt(seatField.getString()))

// for testing purposes only ); /* if something was ordered, then add that item */ if (itemScreenItem == null) { Display.getDisplay(this).

setCurrent(myOrderScreen); } else { orderItemScreenItem(); }

Page 105: Java Application for Bluetooth

96

} else if (s.equals(myOrderScreen)) { switch (myOrderScreen.getSelectedIndex()) { case 0:

changeList(viewOrderScreen, myOrderInstance.getOrder()); viewOrderScreen.setTitle("Total order: "+ myOrderInstance.getTotalPriceAsString());

Display.getDisplay(this). setCurrent(viewOrderScreen);

break; case 1: Display.getDisplay(this).

setCurrent(menuScreen); break; case 2:

changeList(viewOrderScreen, myOrderInstance.getOrder());

Display.getDisplay(this). setCurrent(viewOrderScreen);

break; case 3: myOrderInstance.submitOrder(); myOrderInstance.refreshOrder();

orderComplete.setString("Thank you for your order. Feel free to order more items.");

Display.getDisplay(this). setCurrent(orderComplete, titleScreen);

break; } } } else if (commandLabel.equals("Back")) { /* Item screen is set to null for the seat number screen to determine what screen to return to. */ itemScreenItem = null; if (s.equals(menuScreen)) { Display.getDisplay(this).setCurrent(titleScreen); } else if (s.equals(typeScreen)) { Display.getDisplay(this).setCurrent(menuScreen); } else if (s.equals(itemScreen)) { Display.getDisplay(this).setCurrent(typeScreen); } else if (s.equals(requestNameScreen)) { Display.getDisplay(this).setCurrent(titleScreen); } else if (s.equals(requestSeatScreen))

Page 106: Java Application for Bluetooth

97

{ Display.getDisplay(this).

setCurrent(requestNameScreen); } else if (s.equals(myOrderScreen)) { Display.getDisplay(this).setCurrent(titleScreen); } else if (s.equals(viewOrderScreen)) { Display.getDisplay(this).setCurrent(myOrderScreen); } else if (s.equals(getFlightCodeScreen)) { Display.getDisplay(this).setCurrent(myOrderScreen); } } else if (commandLabel.equals("Order")) { if (myOrderInstance == null) { Display.getDisplay(this).setCurrent(requestNameScreen); } else { orderItemScreenItem(); } } else if (commandLabel.equals("Remove")) { Vector theOrder = myOrderInstance.getOrder(); int selectedIndex = viewOrderScreen.getSelectedIndex(); if (selectedIndex >= 0) {

MenuItem itemRemoved = (MenuItem) theOrder.elementAt(selectedIndex); String alertText = itemRemoved.name + " has been removed from your order";

theOrder.removeElementAt(selectedIndex); removedItem.setString(alertText); } else { removedItem.setString("No item to remove"); }

Display.getDisplay(this).setCurrent(removedItem, myOrderScreen);

} else if (commandLabel.equals("Exit")) { notifyDestroyed(); }

Page 107: Java Application for Bluetooth

98

} // order the item currently selected for the item screen private void orderItemScreenItem() {

String alertText = itemScreenItem.name + " has been added to your order";

myOrderInstance.addItem(itemScreenItem); addedItem.setString(alertText); Display.getDisplay(this).setCurrent(addedItem, myOrderScreen); } // initlise the screens private void initApp() { /* INITALISE SCREENS */ canvas = new MyCanvas( this ); /* Title Screen */ titleScreen = new Form("Welcome"); titleScreen.addCommand(OKCommand); titleScreen.addCommand(exitCommand); titleChoices.append("View menu", null); titleChoices.append("View my order", null); titleChoices.append("Check my flight time", null); titleScreen.append(titleChoices); titleScreen.setCommandListener(this); titleScreen.setTicker(new Ticker("Go to View my Order to submit your order"));

/* Menu Screen */ menuScreen = new List("Menu", List.EXCLUSIVE, menuItemTypes, null); menuScreen.addCommand(OKCommand); menuScreen.addCommand(backCommand); menuScreen.setCommandListener(this); /* Type Screen */ typeScreen = new List("Type", List.EXCLUSIVE); typeScreen.addCommand(OKCommand); typeScreen.addCommand(backCommand); typeScreen.setCommandListener(this); /* Item Screen */ itemScreen = new Form ("Item"); itemScreen.append(itemDescription); itemScreen.addCommand(orderCommand); itemScreen.addCommand(backCommand); itemScreen.setCommandListener(this); /* RequestName Screen */ requestNameScreen = new Form ("Please enter your name"); requestNameScreen.append(nameField); requestNameScreen.addCommand(OKCommand); requestNameScreen.addCommand(backCommand); requestNameScreen.setCommandListener(this);

Page 108: Java Application for Bluetooth

99

/* RequestSeat Screen */ requestSeatScreen = new Form ("Please enter your seat number"); requestSeatScreen.append(seatField); requestSeatScreen.addCommand(OKCommand); requestSeatScreen.addCommand(backCommand); requestSeatScreen.setCommandListener(this); /* Flgiht code */ getFlightCodeScreen = new Form ("Please enter you flight code"); getFlightCodeScreen.append(flightCodeField ); getFlightCodeScreen.addCommand(OKCommand); getFlightCodeScreen.addCommand(backCommand); getFlightCodeScreen.setCommandListener(this); /* myOrder Screen */ myOrderScreen = new List("My Order", List.EXCLUSIVE, myOrderOptions, null);

myOrderScreen.addCommand(OKCommand); myOrderScreen.addCommand(backCommand); myOrderScreen.setCommandListener(this); /* viewOrder Screen */ viewOrderScreen = new List("My Order", List.EXCLUSIVE); viewOrderScreen.addCommand(removeCommand); viewOrderScreen.addCommand(backCommand); viewOrderScreen.setCommandListener(this); /* addedItem Screen */ addedItem = new Alert ("Item added"); addedItem.setType(AlertType.CONFIRMATION); addedItem.setTimeout(Alert.FOREVER); /* removeItem Screen */ removedItem = new Alert ("Item removed"); /* invalidData Screen */ invalidData = new Alert ("Invalid Data"); invalidData.setType(AlertType.CONFIRMATION); invalidData.setTimeout(Alert.FOREVER); /* orderComplete Screen */ orderComplete = new Alert ("OrderComplete"); orderComplete.setType(AlertType.CONFIRMATION); orderComplete.setTimeout(Alert.FOREVER); /* orderComplete Screen */ flightTime = new Alert ("Flight Status"); flightTime.setType(AlertType.CONFIRMATION); flightTime.setTimeout(Alert.FOREVER); /* INITALISE MENU */ try { RemoteMethods.viewMenu ( startersMenu, mainCoursesMenu,

Page 109: Java Application for Bluetooth

100

desertsMenu, drinksMenu ); } catch (Exception e) { } } /* Change the contents of the list given a vector of menu items. */ private void changeList ( List listToChange, Vector vectorToInsert ) { int listSize = listToChange.size(); int vectorSize = vectorToInsert.size(); int count; for (count = 0; count < vectorSize; count++) {

listToChange.append(((MenuItem)vectorToInsert.elementAt(count)).name, null);

} for (count = 0; count < listSize; count++) { listToChange.delete(0); } } }

Page 110: Java Application for Bluetooth

101

Class: MenuItem.java

/* * MenuItem * * - Class for holding menu item information */ public class MenuItem { public String name; public String description; public int priceDollars; public int priceCents; public MenuItem ( String pName, String pDescription, int pPriceDollars, int pPriceCents ) { name = pName; description = pDescription; priceDollars = pPriceDollars; priceCents = pPriceCents; } }

Class: MyOrder.java

/* * MyOrder.java - Class for managing orders * Author: Benjamin Williams * Last modified: 5/10/2002 */ import java.util.*; public class MyOrder { private String firstName; private int tableNumber; private int orderNumber; private Vector order; // Constructor public MyOrder ( String pFirstName, int pTableNumber,

Page 111: Java Application for Bluetooth

102

int pOrderNumber ) { firstName = pFirstName; tableNumber = pTableNumber; orderNumber = pOrderNumber; order = new Vector(); } // add an item to the order public void addItem (MenuItem pItem) { order.addElement(pItem); } // remove an item from the order public void removeItem (MenuItem pItem) { order.removeElement(pItem); } // submit the user's order to the server public void submitOrder () { int length = order.size(); int count; try { for (count = 0; count < length; count++) { RemoteMethods.orderItem ( orderNumber, ((MenuItem) order.elementAt(count)).name ); } } catch (Exception e) { } } // return the order Vector public Vector getOrder() { return order; } // clear the order public void refreshOrder() { order = new Vector(); }

Page 112: Java Application for Bluetooth

103

// return the total price of the order as a string public String getTotalPriceAsString() { int length = order.size(); int count; int totalDollars = 0; int totalCents = 0; for (count = 0; count < length; count++) {

totalDollars = totalDollars + ((MenuItem) order.elementAt(count)).priceDollars; totalCents = totalCents + ((MenuItem) order.elementAt(count)).priceCents;

} totalDollars = totalDollars + (totalCents / 100); totalCents = totalCents % 100; if (totalCents < 10) { return "$" + totalDollars + ".0" + totalCents; } else { return "$" + totalDollars + "." + totalCents; } } }

Class: CLDCTransport.java

/* * CLDCTransport.java - Bluetooth Transport interface invoke * Author: Benjamin Williams * Last modified: 5/10/2002 */ import com.wingfoot.soap.transport.*; import com.wingfoot.soap.encoding.*; import com.wingfoot.soap.*; import com.wingfoot.soap.transport.Transport; import java.util.*; import java.io.*; import javax.microedition.io.*; public class CLDCTransport implements Transport { private String url; private String header; private byte [] response; private byte [] response2; /** Constructor */

Page 113: Java Application for Bluetooth

104

public CLDCTransport (String theUrl) { response = new byte[1000]; url = new String(theUrl); } /** Sends a http message */

public byte[] call(byte[] payload) throws SOAPException, IOException

{ String resource = ""; String host = new String(url.substring(7)); String message = new String (payload, "UTF8"); if (!url.startsWith("http://")) {

throw new SOAPException("URL must start with http://");

} int endOfHost = host.indexOf("/"); resource = new String(host.substring(endOfHost)); host = new String(host.substring(0, endOfHost)); /* Construct the header */

header = new String ("POST " + resource + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Content-Type: text/xml; charset=utf-8\r\n" + "Content-Length: " + payload.length + "\r\nSoap Action: http://localhost/menu\r\n\r\n");

/* Open a RFCOMM connection to the gateway and send the header along with the SOAP request */

StreamConnection conn = (StreamConnection) Connector.open("btspp://00d0b7034b3e:2");

PrintStream out =

new PrintStream( conn.openOutputStream() ); out.println(header + message); out.flush(); /* Read the raw HTTP reply.*/ InputStream in = conn.openInputStream(); int position = 0; int sizeOfBody = removeHeaders(in); response = new byte[sizeOfBody + 1]; // Read the body of the response for (int count = 0; count < sizeOfBody; count++) { if ((response[position++] = (byte) in.read()) < 0) {

throw new SOAPException("Error reading response");

}

Page 114: Java Application for Bluetooth

105

} conn.close(); return response; } /* removeHeaders - Keeps removing headers from the input stream until an error or success response is reached */

private int removeHeaders(InputStream in) throws SOAPException, IOException

{ int position = 0; byte [] responseHeader = new byte[500]; String headerString; String contentLength; int characterRead = 0; int lastCharacter = 0; /* Remove the header */

while( ((characterRead = in.read()) != -1) && !((lastCharacter == 10) && (characterRead == 13)) )

{ lastCharacter = characterRead; responseHeader[position++] = (byte) characterRead; } // Read the last line feed in.read(); if (characterRead < 0) { throw new SOAPException("Error reading response"); }

headerString = new String (responseHeader, "UTF8"); /* Determine response code */ switch (headerString.charAt(9)) { case '1' : return removeHeaders(in); case '2' :

contentLength = headerString.substring(headerString.indexOf("Content-Length:") + 16); return Integer.parseInt(contentLength.substring(0, contentLength.indexOf((char) 13)));

default : throw new SOAPException("HTTP Error"); } } }

Page 115: Java Application for Bluetooth

106

Appendix E – Server Application Source Code

Option Explicit Public Type menuItem itemName As String ItemDescription As String ItemType As String ItemPriceCents As Integer ItemPriceDollars As Integer End Type Public Type orderList items() As String End Type Public Type menu itemList() As menuItem End Type Public Function newOrderNumber(ByVal customerName As String, ByVal _ customerSeat As Integer) _ As Integer 'Open the order server db Dim orderServerDB As Database Set orderServerDB = OpenDatabase("c:\cafe\OrderServer.mdb") Dim ordersRS As Recordset Dim ordersNumbersRS As Recordset Set ordersRS = orderServerDB.OpenRecordset("Orders", dbOpenDynaset) Set ordersNumbersRS = _ orderServerDB.OpenRecordset("OrderNumbers", dbOpenDynaset) 'Retreive the highest record number Dim highestRecordNumber ordersNumbersRS.Edit highestRecordNumber = ordersNumbersRS!highestOrderNumber + 1 ordersNumbersRS!highestOrderNumber = highestRecordNumber ordersNumbersRS.Update 'Add a new order to the DB ordersRS.AddNew ordersRS!orderNumber = highestRecordNumber ordersRS!customerName = customerName ordersRS!SeatNumber = customerSeat ordersRS.Update newOrderNumber = highestRecordNumber 'highestRecordNumber End Function Public Function orderItem(ByVal orderNumber As Integer, _ ByVal itemName As String) _ As Integer

Page 116: Java Application for Bluetooth

107

'Open the order server db Dim orderServerDB As Database Dim orderItemsRS As Recordset Set orderServerDB = OpenDatabase("c:\cafe\OrderServer.mdb") Set orderItemsRS = orderServerDB.OpenRecordset("OrderItems",_ dbOpenDynaset) 'Add a new item to the order orderItemsRS.AddNew orderItemsRS!orderNumber = orderNumber orderItemsRS!itemName = itemName orderItemsRS.Update orderItem = orderNumber End Function Public Function viewMenu() As menu 'Create an array of menu items and return to the caller 'Open the order server db Dim orderServerDB As Database Set orderServerDB = OpenDatabase("c:\cafe\OrderServer.mdb") 'Open the items table Dim itemsRS As Recordset Set itemsRS = orderServerDB.OpenRecordset("Items", dbOpenDynaset) Dim menuSize As Integer Dim menuItemCounter As Integer itemsRS.MoveLast menuSize = itemsRS.RecordCount itemsRS.MoveFirst Dim currentMenu As menu ReDim currentMenu.itemList(menuSize) For menuItemCounter = 0 To menuSize - 1 currentMenu.itemList(menuItemCounter).itemName = itemsRS!Name

currentMenu.itemList(menuItemCounter).ItemDescription = _ itemsRS!Description

currentMenu.itemList(menuItemCounter).ItemType = itemsRS!Type currentMenu.itemList(menuItemCounter).ItemPriceDollars = _ itemsRS!PriceDollars currentMenu.itemList(menuItemCounter).ItemPriceCents = _ itemsRS!PriceCents

itemsRS.MoveNext Next viewMenu = currentMenu End Function Public Function getFlightStatus(ByVal flightCode As String) As String 'Create an array of menu items and return to the caller 'Open the order server db Dim orderServerDB As Database

Page 117: Java Application for Bluetooth

108

Set orderServerDB = OpenDatabase("c:\cafe\OrderServer.mdb") 'Open the items table Dim flightStatusRS As Recordset Set flightStatusRS = orderServerDB.OpenRecordset("FlightStatus",_ dbOpenDynaset) Dim flightSize As Integer Dim count As Integer For count = 1 To flightStatusRS.RecordCount If flightStatusRS!flightCode = flightCode Then getFlightStatus = flightStatusRS!Status flightStatusRS.MoveNext End If End Function

Page 118: Java Application for Bluetooth

109

Appendix F – Gateway Source Code

#include <stdio.h> #include <netinet/in.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <termios.h> #include <sys/ioctl.h> #include <fcntl.h> #include <errno.h> #define SYSCALL(v,x,s) if (((v) = (x)) < 0) { perror(s); exit(errno);} #define TIMEOUT_SEC 60 #define TIMEOUT_SERVER 20 #define HEADER_BUFFER_SIZE 300 #define BODY_BUFFER_SIZE 5000 struct sockaddr_in * serverAddr; /* * Exit routine. The process exits through here */ void gatewayExit ( char * message, FILE * theChannel ) { fprintf(stderr, message); if (theChannel != 0) { fclose(theChannel); } exit(0); } /* * Note: this needs to be modified for the proxy server */ static int createSocket ( char * host ) { struct hostent * hostInfo; struct sockaddr_in addr; int theSocket;

Page 119: Java Application for Bluetooth

110

serverAddr = (struct sockaddr_in *) malloc (sizeof (struct sockaddr_in));

/* Set server port and address family */ serverAddr -> sin_family = AF_INET; serverAddr -> sin_port = htons(80); /* Extract the Hostname */ hostInfo = gethostbyname(host); if (hostInfo == NULL) { gatewayExit("Unknown host", 0); } serverAddr->sin_addr = *(struct in_addr *) hostInfo->h_addr; if ((theSocket = socket(PF_INET, SOCK_STREAM, 0)) < 0) { gatewayExit("Error creating socket", 0); }

if ((connect(theSocket, (struct sockaddr*)serverAddr, sizeof (struct sockaddr_in))) < 0)

{ gatewayExit("Error connecting socket", 0); } return theSocket; } int getContent ( FILE * channel ) { fd_set set; struct timeval timeout; char headerBuffer[HEADER_BUFFER_SIZE]; char bodyBuffer[BODY_BUFFER_SIZE]; int channelDescriptor; int lastCharacter = 'x'; int thisCharacter = 'y'; int position = 0; int payloadLength; int theSocket; int count; char * contentLengthString; char hostString[100]; char fixedHostString[100]; //Initalise set channelDescriptor = fileno(channel); FD_ZERO(&set); FD_SET(channelDescriptor, &set); //Initalise timeout timeout.tv_sec = TIMEOUT_SEC; timeout.tv_usec = 0; if (select(FD_SETSIZE, &set, NULL, NULL, NULL)!= 1)

Page 120: Java Application for Bluetooth

111

{ gatewayExit("Timeout or error receiving header", channel); } /* Remove the header */

while( ((thisCharacter = fgetc(channel)) != EOF) && !((lastCharacter == 10) && (thisCharacter == 10)) )

{ if (thisCharacter < 0) { gatewayExit("Cannot read from channel", channel); } lastCharacter = thisCharacter; headerBuffer[position++] = (char) thisCharacter; if (position > (HEADER_BUFFER_SIZE - 20)) { gatewayExit("Header Buffer Overrun", channel); } if (select(FD_SETSIZE, &set, NULL, NULL, &timeout)!= 1) { gatewayExit("Timeout or error receiving header", channel); } } /* Store last linefeed and convert to string*/ headerBuffer[position++] = thisCharacter; headerBuffer[position + 1] = 0; /* Get the content length */ contentLengthString =

(char *) memmem (headerBuffer, position, "Content-Length: ", 16) + 16;

payloadLength = atoi(contentLengthString); /* Read the body */ for (count = 0; count < payloadLength; count++) { if (select(FD_SETSIZE, &set, NULL, NULL, &timeout)!= 1) {

gatewayExit("Timeout or error receiving body", channel);

} bodyBuffer[count] = fgetc(channel); } /* Get the string with the hostname */ strcpy ( hostString, ((char *) memmem (headerBuffer, position, "Host: ", 6) + 6) ); /* Get the hostname from the string*/ for (count = 0; count < strlen(hostString); count++) { if (hostString[count] == (char) 10) { hostString[count] = (char) 0 ;

Page 121: Java Application for Bluetooth

112

} } fflush(stdout); /*Open socket*/ theSocket = createSocket(hostString); /* Send the header */ if (send(theSocket, headerBuffer, position, 0) < 0) { gatewayExit("Error sending header", channel); } /* Send the body */ if (send(theSocket, bodyBuffer, payloadLength, 0) < 0) { gatewayExit("Error sending body", channel); } return theSocket; } int getServerReply ( int theSocket, FILE * channel ) { fd_set set; struct timeval timeout; char headerBuffer[HEADER_BUFFER_SIZE]; int lastCharacter = 'x'; int thisCharacter = 'y'; int position = 0; int payloadLength; int count; char * contentLengthString; char responseCode; //Initalise set FD_ZERO(&set); FD_SET(theSocket, &set); //Initalise timeout bzero(&timeout, sizeof(timeout)); timeout.tv_sec = TIMEOUT_SERVER; timeout.tv_usec = 0; // Wait for server response if (select(FD_SETSIZE, &set, NULL, NULL, &timeout)!= 1) { gatewayExit("Timeout receiving header1", channel); } /* Remove the header */

while((recv(theSocket, &thisCharacter, 1, 0) != -1) && !((lastCharacter == 10) && (thisCharacter == 13)) )

{

Page 122: Java Application for Bluetooth

113

lastCharacter = thisCharacter; headerBuffer[position++] = (char) thisCharacter; if (select(FD_SETSIZE, &set, NULL, NULL, &timeout)!= 1) { gatewayExit("Timeout receiving header1", channel); } } //Get the last line feed headerBuffer[position++] = (char) thisCharacter; recv(theSocket, &thisCharacter, 1, 0); headerBuffer[position++] = (char) thisCharacter; if (thisCharacter < 0) { gatewayExit("Error receiving header1", channel); }else { /* store the last line feed */ headerBuffer[position++] = thisCharacter; } /* Get the response code */ headerBuffer[position] = (char) 0; responseCode = headerBuffer[9]; /* Determine response code */ if (responseCode == '1') { printf("Got header 1"); /* Send the header */ if (fputs(headerBuffer, channel) < 0) {

gatewayExit("Error sending response header", channel);

} printf("Sent header 1"); fflush(stdout); return 0; } else if (responseCode == '2') { /* Get the content length */ contentLengthString =

(char *) memmem (headerBuffer, position, "Content-Length: ", 16) + 16;

payloadLength = atoi(contentLengthString); /* Send the header */ if (fputs(headerBuffer, channel) < 0) {

gatewayExit("Error sending response header2", channel);

}

Page 123: Java Application for Bluetooth

114

for (count = 0; count < payloadLength; count++) { /* Send the rest of the body */

if (select(FD_SETSIZE, &set, NULL, NULL, &timeout)!= 1)

{ gatewayExit("Timeout receiving body", channel);

} recv(theSocket, &thisCharacter, 1, 0); /* Send the character */ if (fputc(thisCharacter, channel) < 0) {

gatewayExit("Error sending response body", channel);

} fflush(channel); } }else {

/* Send the header */ if ( fputs(headerBuffer, channel) < 0) {

gatewayExit("Error sending response header", channel);

} } return 1; } int main (int argc, char **argv) { int theSocket; FILE * theChannel; struct termios t; int theChannelDescriptor; int ret;

SYSCALL(theChannel, fopen("/dev/ttyBT0","r+b"), "SERVERCHANNEL");

theChannelDescriptor = fileno(theChannel); ioctl(theChannelDescriptor, TCGETS, &t);

t.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);

t.c_iflag |= IGNCR; //Ignore the carriage return t.c_iflag |= IMAXBEL; t.c_cflag |= CLOCAL; t.c_cflag &= ~CRTSCTS; ioctl(theChannelDescriptor, TCSETS, &t); theSocket = getContent(theChannel);

Page 124: Java Application for Bluetooth

115

SYSCALL(ret, fclose(theChannel), "FCLOSECHANNEL");

SYSCALL(theChannel, fopen("/dev/ttyBT0","r+b"), "REOPENCHANNEL");

theChannelDescriptor = fileno(theChannel); ioctl(theChannelDescriptor, TCGETS, &t); //t.c_oflag |= ONLCR; t.c_cflag |= CLOCAL; t.c_cflag &= ~CRTSCTS; ioctl(theChannelDescriptor, TCSETS, &t); while (getServerReply(theSocket, theChannel) == 0){}; SYSCALL(ret, fclose(theChannel), "FCLOSECHANNEL"); gatewayExit("Goodbye", theChannel); return 1; }

Page 125: Java Application for Bluetooth

116

Appendix G – Old Java Bluetooth Interface Source Code

/* * ConnectionImpl_btspp.java * Written by Benjamin Williams * Based on the comm.c serial port code in the * CLDC reference implementation by Sun Microsystems */ package org.me4se.impl; import javax.microedition.io.*; import javax.microedition.midlet.*; import java.io.*; import java.net.*; import java.util.*; public class ConnectionImpl_btspp extends ConnectionImpl implements StreamConnection { public int handle; private PrivateInputStream in; private PrivateInputStream out; /* * Open a RFCOMM connection */ public void open (String url, int mode, boolean timeouts) throws IOException { int cut = url.lastIndexOf (':'); String btAddr; int channel; // Extract the address and channel number from the URL btAddr = url.substring (8, cut); channel = Integer.parseInt (url.substring (cut+1)); handle = RFCOMM.openRFCOMMJava(btAddr, channel); in = new PrivateInputStream(this); out = new PrivateOutputStream(this); } public InputStream openInputStream () throws IOException { return in; } public DataInputStream openDataInputStream () throws IOException { return new DataInputStream (openInputStream ()); } public OutputStream openOutputStream () throws IOException { return out; }

Page 126: Java Application for Bluetooth

117

public DataOutputStream openDataOutputStream () throws IOException { return new DataOutputStream (openOutputStream ()); } public void close () throws IOException { RFCOMM.closeRFCOMMJava(handle); } /* * Input stream for the connection */ class PrivateInputStream extends InputStream { byte[] buf = new byte[1]; ConnectionImpl_btspp parent; /* * Constructor */ public PrivateInputStream(ConnectionImpl_btspp parent) throws IOException { this.parent = parent; } /* * Check the stream is open */ void ensureOpen() throws IOException { if (parent == null) { throw new IOException("Stream closed"); } } /* * Reads the next byte of data from the input stream. */ synchronized public int read() throws IOException { if (RFCOMM.readRFCOMMjava(parent.handle, buf, 0, 1) > 0) { return (buf[0] & 0xFF); } return -1; } /* * Reads up to len bytes of data from the input stream into * an array of bytes. */ synchronized public int read(byte b[], int off, int len) throws IOException { ensureOpen(); if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException();

Page 127: Java Application for Bluetooth

118

} return RFCOMM.readRFCOMMJava(parent.handle, b, off, len); } /** * Close the stream * * @exception IOException if an I/O error occurs. */ public synchronized void close() throws IOException { if (parent != null) { RFCOMM.closeRFCOMMJava(parent.handle); parent = null; } } } /* * Output stream for the connection */ class PrivateOutputStream extends OutputStream { ConnectionImpl_btspp parent; byte[] buf = new byte[1]; /* * Constructor */ public PrivateOutputStream(ConnectionImpl_btspp p) { parent = p; } /* * Check the stream is open */ void ensureOpen() throws IOException { if (parent == null) { throw new IOException("Stream closed"); } } /* * Writes the specified byte to this output stream. */ synchronized public void write(int b) throws IOException { buf[0] = (byte)b; RFCOMM.writeRFCOMMJava(parent.handle, buf, 0, 1); } /* * Writes len bytes from the specified byte array */ synchronized public void write(byte b[], int off, int len) throws IOException { int test;

Page 128: Java Application for Bluetooth

119

ensureOpen(); if (len <= 0) { return; } RFCOMM.writeRFCOMMJava(parent.handle, b, off, len); } /* File: RFCOMM.c Author: Benjamin Williams This file compilies to a JNI Library to support establishing a RFCOMM Bluetooth connection. This Library uses the BTCore Library in the AFfix Bluetooth stack. It is designed for cross-compilation to the Ipaq. */ #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <linux/types.h> #include <linux/if.h> #include <linux/ioctl.h> #include <stdint.h> #include <string.h> #include <jni.h> #include "org_me4se_impl_RFCOMM.h" #define BDADDR_ANY (BD_ADDR){{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}} #define PF_AFFIX 27 #define BTPROTO_RFCOMM 2 // Define bluetooth address type typedef struct { __u8 bda[6]; }__attribute__ ((packed)) BD_ADDR, *BDADDR; struct sockaddr_affix { sa_family_t family; BD_ADDR bda; uint16_t port; BD_ADDR local; /* local Bluetooth adapter to connect to */ }; int str2bda(BD_ADDR *p, char *str) { int i, val, err; char *res=(char*)p;

Page 129: Java Application for Bluetooth

120

for(i = 5; i >= 0; i--) { err = sscanf(str, "%2x", &val); if( err == 0 ) return 0; res[i] = val; if( i == 0 ) break; if( str == 0 ) return 0; str++; str++; } return 1; } /* * Class: RFCOMM * Method: openRFCOMM * Signature: (Ljava/lang/String;I)I */ JNIEXPORT jint JNICALL Java_org_me4se_impl_RFCOMM_openRFCOMM (JNIEnv *env, jclass class, jstring btaddrString, jint channel) { int error; int socketFD; int count; BD_ADDR connectionAddr; struct sockaddr_affix saddr; int nbytes; error = str2bda(&connectionAddr, addr); if (error == 0){ printf("Error with string"); } socketFD = socket(PF_AFFIX, SOCK_STREAM, BTPROTO_RFCOMM); if( socketFD < 0 ) { perror("Error with socket"); fflush(stdout); } saddr.bda = connectionAddr; saddr.port = 2; saddr.local = BDADDR_ANY;

error = connect(socketFD, (struct sockaddr*)&saddr, sizeof(saddr));

if( error < 0 ) { perror("Error with connection"); close(socketFD); } nbytes = write ( socketFD, test, 6/*(int) length */); if (nbytes < 0){

Page 130: Java Application for Bluetooth

121

perror("Error with writing to handle"); } sleep(5); nbytes = write ( socketFD, test, 6/*(int) length */); sleep(5); close(socketFD); return (jint) -1; //socketFD; } /* * Class: RFCOMM * Method: closeRFCOMM * Signature: (I)I */ JNIEXPORT jint JNICALL Java_org_me4se_impl_RFCOMM_closeRFCOMM (JNIEnv *env, jclass class, jint socketHandle) { close((int) socketHandle); return (jint) 1; } /* * Class: RFCOMM * Method: readRFCOMM * Signature: (I[BII)I */ JNIEXPORT jint JNICALL Java_org_me4se_impl_RFCOMM_readRFCOMM (JNIEnv *env, jclass class, jint socketHandle, jbyteArray readBuffer, jint offset, jint length) { jbyte *buffer = (*env)->GetByteArrayElements(env, readBuffer, 0); int nbytes; //read data from the socket nbytes = read ((int) socketHandle, buffer + (int)offset, (int) length); (*env)->ReleaseByteArrayElements(env, readBuffer, buffer, 0); return (jint) nbytes; } /* * Class: RFCOMM * Method: writeRFCOMM * Signature: (I[BII)I */ JNIEXPORT jint JNICALL Java_org_me4se_impl_RFCOMM_writeRFCOMM

(JNIEnv *env, jclass class, jint socketHandle, jbyteArray writeBuffer, jint offset, jint length)

{ jbyte *buffer = (*env)->GetByteArrayElements(env, writeBuffer, 0);

int nbytes;

Page 131: Java Application for Bluetooth

122

//read data from the socket nbytes = write ( socketHandle, buffer, (int)offset, (int) length */);

(*env)->ReleaseByteArrayElements(env, writeBuffer, buffer, 0); if (nbytes < 0){ printf("Error with writing to handle %d", socketHandle); } return (jint) nbytes; }

Page 132: Java Application for Bluetooth

123

Appendix H – Revised Java Bluetooth Interface Source Code

/* TestRF.c by Benjamin Williams Forms a RFCOMM connection with stdin as input and stdout as output */ #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <linux/types.h> #include <linux/if.h> #include <linux/ioctl.h> #include <stdint.h> #include <string.h> #define BDADDR_ANY (BD_ADDR){{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}} #define PF_AFFIX 27 #define BTPROTO_RFCOMM 2 // Define bluetooth address type typedef struct { __u8 bda[6]; }__attribute__ ((packed)) BD_ADDR, *BDADDR; struct sockaddr_affix { sa_family_t family; BD_ADDR bda; uint16_t port; BD_ADDR local; /* local Bluetooth adapter to connect to */ }; int str2bda(BD_ADDR *p, char *str) { int i, val, err; char *res=(char*)p; for(i = 5; i >= 0; i--) { err = sscanf(str, "%2x", &val); if( err == 0 ) return 0; res[i] = val; if( i == 0 ) break; if( str == 0 ) return 0; str++; str++; } return 1; } int main (int argc, char **argv ) { int error;

Page 133: Java Application for Bluetooth

124

int socketFD; int count; int childPID; BD_ADDR connectionAddr; struct sockaddr_affix saddr; int nbytes; int sendCh; char buff[5000]; error = str2bda(&connectionAddr, argv[1]); if (error == 0) { perror("Error with string"); exit(1); } socketFD = socket(PF_AFFIX, SOCK_STREAM, BTPROTO_RFCOMM); if( socketFD < 0 ) { perror("Error with socket"); exit(1); } saddr.bda = connectionAddr; saddr.port = atoi(argv[2]); saddr.local = BDADDR_ANY;

error = connect(socketFD, (struct sockaddr*)&saddr, sizeof(saddr));

if( error < 0 ) { perror("Error with connection"); close(socketFD); } printf("Established connection"); /* Fork the process into a parent and child */ if ((childPID = fork()) < 0) { exit( 2 ); } else { if (childPID > 0) { /* parent process reads from connection and writes to stdout */ while (1){

if ((nbytes = recv(socketFD, buff, 4999, 0)) < 0)

{ perror("bad"); } buff[nbytes] = 0; printf("%s", buff); fflush(stdout); }

Page 134: Java Application for Bluetooth

125

} else { /* child process reads from stdin and writes to connection */ while (1) { while ((sendCh = getc(stdin)) == EOF) { } nbytes = write ( socketFD, &sendCh, 1); } } } close(socketFD); return 1; } package org.me4se.impl; import java.util.*; import java.io.*; public class RFCOMM { protected static OutputStream RFCOMMOut; protected static InputStream RFCOMMIn; /** Method openRFCOMM * - opens an RFCOMM conection * @param BTAddr - Bluetooth address of remote device * @param channel - server channel to connect to * @exception IOException if an I/O error occurs * */ public static int openRFCOMMJava ( String BTAddr, int channel )throws IOException { int handle = 0; Process btctl; String command = "/root/BTint " + BTAddr + " " + channel; btctl = Runtime.getRuntime().exec(command); RFCOMMOut = btctl.getOutputStream(); RFCOMMIn = btctl.getInputStream(); return handle; }

Page 135: Java Application for Bluetooth

126

public static InputStream getInputStream() { return RFCOMMIn; } public static OutputStream getOutputStream() { return RFCOMMOut; } /** Method closeRFCOMMJava * - closes an RFCOMM conection * @param handle - the connection handle to close * @exception IOException if an I/O error occurs * */ public static int closeRFCOMMJava ( int handle ) throws IOException { RFCOMMOut.close(); RFCOMMIn.close(); return 1; } }

Page 136: Java Application for Bluetooth

127

Table of Contents Part 1 – Introduction and basis for research ...................................................................1

1.1 Overview.............................................................................................................1 1.2 Introduction.........................................................................................................1 1.2 The Bluetooth Standard .......................................................................................2 1.2 Basis for the Project.............................................................................................5 1.3 Aims of the project ..............................................................................................7 1.4 Plan for delivering the project goals.....................................................................8

1.4.1 Research and analysis...................................................................................8 1.4.2 Design ..........................................................................................................9 1.4.3 Implementation .............................................................................................9 1.4.4 Evaluation ....................................................................................................9

Part 2 – Research and Analysis....................................................................................11 2.1 Overview...........................................................................................................11 2.2 Overview of the Bluetooth Specification ...........................................................11

2.2.1 The Radio ...................................................................................................11 2.2.2 The Baseband Layer ...................................................................................13 2.2.3 Link Manager Protocol...............................................................................14 2.2.4 Logical Link Control and Adaptation Protocol (L2CAP).............................14 2.2.5 Host Controller Interface ............................................................................15 2.2.6 RFCOMM...................................................................................................15 2.2.7 PPP ............................................................................................................15 2.2.6 OBEX .........................................................................................................16 2.2.7 Service Discovery Protocol.........................................................................16 2.2.8 The Bluetooth Profiles ................................................................................16 2.2.9 Generic Access Profile................................................................................17 2.2.10 Service Discovery Profile..........................................................................18 2.2.11 Serial Port Profile.....................................................................................18 2.2.12 Generic Object Exchange Profile ..............................................................18

2.3 Java 2 Micro Edition .........................................................................................18 2.3.1 Virtual Machine Layer................................................................................20 2.3.2 Configuration Layer ...................................................................................20 2.3.3 Profile Layer...............................................................................................20

2.4 Bluetooth API....................................................................................................21 2.5 Criteria for Bluetooth applications .....................................................................22

2.5.1 Strengths of the technology .........................................................................22 2.5.2 Limitations and restrictions of Bluetooth Technology..................................22

2.6 Other requirements for the experimental application..........................................24 2.7 Market for Bluetooth Applications.....................................................................24

2.7.1 Wireless Commerce ....................................................................................25 2.7.2 Location aware mobile commerce services .................................................26 2.7.3 Mobile Financial Application .....................................................................26 2.7.4 Mobile Advertising......................................................................................27 2.7.5 Proactive Service Management ...................................................................27 2.7.6 Product Location and Shopping ..................................................................27 2.7.7 Information services on public networks .....................................................28 2.7.8 Other non-commercial applications ............................................................28

Page 137: Java Application for Bluetooth

128

2.7.9 Ad-hoc networking and groupware .............................................................28 2.8 Non-functional requirements and criteria to evaluate the end product ................29

2.8.1 Added convenience .....................................................................................29 2.8.2 Speed ..........................................................................................................29 2.8.3 User Interface .............................................................................................29 2.8.4 Security.......................................................................................................30 2.8.5 Reliability ...................................................................................................30

2.9 Choice of application scenario ...........................................................................31 2.9 Critical evaluation of previous work performed on Bluetooth and Java Applications. ...........................................................................................................33

Part 3 – Design............................................................................................................37 3.1 Overview...........................................................................................................37 3.2 System architecture ...........................................................................................37 3.2 System Assumptions .........................................................................................37 3.3 Mobile Device Architecture...............................................................................39 3.4 Network Architecture ........................................................................................41 3.4 Server and Gateway Architecture ......................................................................44 3.5 Mobile device software selection and integration...............................................45

3.5.1 Java Virtual Machine..................................................................................45 3.5.2 Bluetooth Stacks .........................................................................................47 3.5.3 Operating System and JVM.........................................................................48

3.5 Distributed Mobile Services ..............................................................................48 3.6 Middleware Options ..........................................................................................52

3.6.1 COBRA.......................................................................................................52 3.6.2 Java Remote Method Invocation (RMI) .......................................................52 3.6.3 Web Services...............................................................................................53 3.6.4 Simple Object Access Protocol....................................................................53 3.6.5 Web Service Description Language.............................................................54 3.6.6 Universal Description, Discovery, and Integration (UDDI) ........................54 3.6.7 Incorporating Web Services into Bluetooth MIDP Applications ..................54

3.7 Client Application Design .................................................................................55 3.8 Server Design ....................................................................................................59 3.8 Design for the client Java Bluetooth interface ....................................................60 3.8 Gateway Design ................................................................................................64

Part 4 – Implementation ..............................................................................................66 4.1 Overview...........................................................................................................66 4.2 Implementation of the test Client MIDP Application and SOAP server..............66 4.3 Ipaq Setup .........................................................................................................67 4.4 Implementing the gateway.................................................................................68 4.5 Providing the Java interface to the Affix Bluetooth Stack ..................................69 4.6 Implementation and evaluation of the total system.............................................70

Part 5 – Evaluation......................................................................................................71 5.1 Overview...........................................................................................................71 5.2 Outcomes of the project.....................................................................................71 5.3 Evaluation of the final system design.................................................................72

5.3.1 Added convenience .....................................................................................72 5.3.2 Speed ..........................................................................................................72 5.3.3 User Interface .............................................................................................73 5.3.4 Security.......................................................................................................73 5.3.5 Reliability ...................................................................................................73

Page 138: Java Application for Bluetooth

129

5.4 Design Conclusions ...........................................................................................73 5.5 Future Recommendations ..................................................................................74

Bibliography ...............................................................................................................76 Appendix A – MIDP Application Screens ...................................................................80 Appendix B – MIDP Application Classes....................................................................83 Appendix C – MIDP Application Command Actions ..................................................86 Appendix D – MIDP Application Source Code ...........................................................88 Appendix E – Server Application Source Code .........................................................106 Appendix F – Gateway Source Code .........................................................................109 Appendix G – Old Java Bluetooth Interface Source Code..........................................116 Appendix H – Revised Java Bluetooth Interface Source Code ...................................123

Page 139: Java Application for Bluetooth

130

Table of Figures Figure 1. The Bluetooth Protocol Stack .......................................................................12 Figure 2. A Bluetooth Piconet .....................................................................................14 Figure 3. Profiles of the Bluetooth Specification .........................................................17 Figure 4. Java 2 Micro Edition Platform Architecture..................................................19 Figure 5. Topology of the network ..............................................................................39 Figure 6. Architecture of Software Components on the mobile device.........................40 Figure 7. Relationship between interfaces for the Generic Connection Framework......43 Figure 8. Network stacks for the gateway and mobile device.......................................45 Figure 9. Distributed System Layers............................................................................49 Figure 10. Using SOAP with TCP/IP/RFCOMM ........................................................55 Figure 11. Server architecture.....................................................................................59 Figure 12. Database Schema .......................................................................................60 Figure 13. The Interface for the Bluetooth connection classes ....................................62 Figure 14. RFCOMM Class........................................................................................63 Figure 15. The gateway process .................................................................................63 Figure 16. The application running in the emulator......................................................65