49
Automatic Bluetooth Based Information Transfer Between P800 Terminals Tage Borg TRITA-NA-E04159

Automatic Bluetooth Based Information Transfer Between ... · Automatic Bluetooth Based Information Transfer Between P800 Terminals Tage Borg TRITA-NA-E04159 . NADA Numerisk analys

  • Upload
    leminh

  • View
    219

  • Download
    2

Embed Size (px)

Citation preview

Automatic Bluetooth Based InformationTransfer Between P800 Terminals

Tage Borg

TRITA-NA-E04159

NADA

Numerisk analys och datalogi Department of Numerical AnalysisKTH and Computer Science100 44 Stockholm Royal Institute of Technology

SE-100 44 Stockholm, Sweden

Automatic Bluetooth Based InformationTransfer Between P800 Terminals

Tage Borg

TRITA-NA-E04159

Master’s Thesis in Computer Science (20 credits)within the First Degree Programme in Mathematics and Computer Science,

Stockholm University 2004Supervisor at Nada was Stefan Nilsson

Examiner was Stefan Arnborg

Abstract

Social navigation is a research area that deals with how people use clues in theirsurrounding, left by other people, to make decisions and find their way around newareas. The clues are called social trails. At SICS, a service for social navigationcalled MobiTip is being developed. MobiTip uses P800 telephones as a mediatorof social trails. Users of MobiTip will run the application on their P800 phones,which will collect social trails from other users’ P800 phones, as well as use theirown phones to leave their own trails in the form of opinions on objects or places inKista Galleria.

The primary choice of medium for communication between the P800 phoneswas Bluetooth. The short-lived networks between the phones of passers-by that wasenvisioned has hitherto not been evaluated and the practical usefulness of Bluetoothin such applications is uncertain.

Furthermore, the service being developed at SICS will be written in Java. Untilnow it has not been possible to access the Bluetooth hardware on P800 phones fromJava. The planned functionality of MobiTip also requires that Bluetooth communi-cation between two P800 phones should be possible without any user interaction.

These goals were achieved during this Master’s project. The thesis is an evalu-ation of the qualities of Bluetooth with respect to connection setup and data rateperformance as well as an account of the development of the automated Java NativeInterface library.

Automatisk Bluetooth-baserad informationsöverföring

mellan P800-terminaler

Sammanfattning

Social navigation är ett forskningsområde som handlar om hur personer användersig av ledtrådar i sin omgivning för att ta beslut och hitta i nya områden. Ledtrå-darna som avses är sådana som lämnas av andra personer i omgivningen. I dettasammanhang kallas det för sociala spår. På SICS utvecklas en tjänst för social nav-igering kallad MobiTip. Denna nyttjar sig av P800-telefoner som medium för socialaspår. MobiTips användare kommer att köra programmet på sina P800-telefoner, somdå kommer att samla in sociala spår från andra användares telefoner såväl som attanvända sina egna telefoner för att lämna egna sociala spår i form av åsikter omföremål och platser i Kista Galleria.

Förstahandsvalet för kommunikation mellan telefonerna var Bluetooth. De kortli-vade nätverk mellan telefoner tillhörande personer som passerar förbi varandra somman föreställt sig har hittills inte utvärderas. Bluetooths praktiska användbarhet isådana sammanhang har därför varit osäker.

Vidare kommer tjänsten som SICS utvecklar att skrivas i Java. Fram tills nuhar det inte varit möjligt att använda Bluetooth-hårdvaran i P800-telefoner frånJava. Den funktionalitet som planerats för MobiTip kräver också att Bluetooth-kommunikation mellan två P800-telefoner ska vara möjlig utan användarinteraktion.

Dessa mål nåddes under detta examensarbete. Rapporten är en utvärdering avBluetooths egenskaper med avseende på prestanda i uppkoppling och dataöverföring.Dessutom utgör rapporten en redogöresle för utvecklingen av det automatiseradeJava Native Interface-biblioteket.

Contents

1 Introduction 1

1.1 The Mobile Services Project . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Overview of the Master’s Project Goals . . . . . . . . . . . . . . . . 2

1.3 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.4 Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.5 Project Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.6 Thesis Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Hardware and Software Environment 6

2.1 The P800 Smart Phone . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.2 Bluetooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.2.1 Connection Setup in Bluetooth . . . . . . . . . . . . . . . . . 8

2.2.2 Theoretical Performance of Connection Establishment . . . . 9

2.2.3 Theoretical Data Transfer Performance . . . . . . . . . . . . . 9

2.3 The Symbian Operating System . . . . . . . . . . . . . . . . . . . . . 10

2.4 The Symbian API . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.4.1 Processes, Threads and Active Objects . . . . . . . . . . . . . 10

2.4.2 Using Bluetooth in Symbian . . . . . . . . . . . . . . . . . . . 12

2.4.3 Connection Setup On the Sender . . . . . . . . . . . . . . . . 13

2.4.4 Connection Setup On the Receiver . . . . . . . . . . . . . . . 15

2.4.5 Data Exchange . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.5 Personal Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.6 The Java Native Interface . . . . . . . . . . . . . . . . . . . . . . . . 16

2.6.1 JNI Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3 Design and Implementation 19

3.1 Development Environment . . . . . . . . . . . . . . . . . . . . . . . . 19

3.2 The Testing Application . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.2.1 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.2.2 Testing Application Runtime Behaviour . . . . . . . . . . . . 21

3.3 The Java API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.3.1 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

3.3.2 Underlying C++ Implementation . . . . . . . . . . . . . . . . 25

4 Bluetooth Performance Evaluation 26

4.1 Test Rationale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.2 Test Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.3 Test Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.4 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

4.4.1 Connection Setup . . . . . . . . . . . . . . . . . . . . . . . . . 294.4.2 Data Rates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.4.3 Moving Terminals . . . . . . . . . . . . . . . . . . . . . . . . 32

4.5 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

5 Conclusions and Recommendations 36

5.1 Evaluation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375.3 The Performance Requirement . . . . . . . . . . . . . . . . . . . . . 375.4 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

5.4.1 Further JNI Development . . . . . . . . . . . . . . . . . . . . 385.4.2 Research Topics . . . . . . . . . . . . . . . . . . . . . . . . . . 38

References 40

A Glossary 43

Chapter 1

Introduction

Finding one’s way around in new surroundings is usually a task of trial and error.Under ideal conditions, directions in the form of signs and maps are available fornewcomers to use. But these are often not enough – seeing the location of allrestaurants in a shopping mall on a map does not convey any information about thequality of the food served or the level of service offered. By following the stream ofpeople heading toward a restaurant and observing the number of persons choosinga certain establishment, a first time visitor can both find a place to eat and judgethe popularity, and thus presumably, the quality of the restaurant in question.

A newcomer that acts on clues in the surroundings in this manner is followingsocial trails thereby using social navigation [10] to reach his or her goals. It isobvious that every person unconsciously leaves such trails around him-/herself at alltimes, not only in “the real world” but also in the more virtual world of computers,computer networks or cellular telephone networks.

One can also envision systems that allow people to actively leave trails, such ascasting votes on objects or locations around them, and performing social navigationwith the help of such trails, left by other persons. This has been explored in theKalas project [10] which implemented a recipe web site, where users could cast votesand comment on recipes. The medium used in Kalas was a web site on Internet butit is not hard to imagine other conduits for information and other applications forthe trails collected.

One such scenario is using hand held devices to create, collect and spread socialtrails in the real world. This thesis project explores the feasibility of using Bluetoothas the mediator of social trails for services running on mobile phones.

1.1 The Mobile Services Project

Mobile Services – is a joint project between the HUMLE laboratory at SICS1, theFuture Applications Lab at Viktoria Institutet2 and the Mobility Studio at Inter-

1http://www.sics.se/humle/2http://bond.viktoria.gu.se/fal/

1

active Institute3, sponsored by Stiftelsen för Strategisk Forskning4. The goal ofMobile Services is to develop new services and the necessary associated supportingtechnology for the next generation of mobile services.

The Mobile Services project is divided into five different research areas:

1. How to interpret and transmit users’ feelings and moods in mobile settings,

2. how to create social mobile services,

3. how to exploit mobility in entertainment services,

4. how to improve mobile services by using interfaces that use multiple types ofmedia, and

5. how to support collaboration by means of mobile activities.

Social navigation is one of the subjects being looked at as a part of the researchconcerning the creation of social services. One part of this work is the MobiTipapplication which is being developed at SICS. MobiTip will run on Sony EricssonP800 and P900 telephones and allow the user to vote for or against shops and otherreal-world entities in the Kista Galleria shopping mall. The votes are the social trailsof this application and will be used to create recommendations on services and shopsin the mall for other users. Communication between the users’ mobile phones andbetween mobile phones and the stationary parts of the system (Bluetooth equippedcomputers called “hotspots”) is envisioned to be accomplished through Bluetooth,the hardware for which is present on the P800 and P900 handsets.

1.2 Overview of the Master’s Project Goals

The goals of this Master’s project were twofold and defined in cooperation withMartin Svensson, the supervisor at SICS. First, an evaluation of the feasibility ofusing Bluetooth as a medium for transferring data between P800 terminals runningMobiTip was needed. The core questions regarding the usefulness of Bluetooth inthis application was whether the time needed for connection setup was short enoughand whether the practical transfer speeds were high enough for the purposes of theMobile Services project.

The second goal was to implement a prototype Bluetooth library for Java, usingJNI, to make a Java implementation of MobiTip possible rather than having toresort to C++. The features envisioned for MobiTip requires that the connectionsbetween terminals are fully automated, in the sense that no user interaction shouldbe required to set up links and exchange data between P800s that may or may nothave met before.

3http://www.interactiveinstitute.se/mobility/4http://www.stratresearch.se/

2

1.3 Related Work

Much of the research that has been done on Bluetooth concern the formation andoverall throughput of Bluetooth networks (called piconets) and scatternets, whichare piconets that are interconnected through shared peers.

For example, Miklós et al. [7] discuss how to maximize data throughput inBluetooth scatternets by optimizing different parameters of the scatternet formation.This article and several other cover algorithmic or other theoretical aspects of thesubject.

The issues of Bluetooth performance in terms of connection setup and datathroughput between individual Bluetooth devices have also been covered, but inmuch fewer articles and technical reports and mostly on the level of looking at theconnection setup protocol. One thing that most of the articles written on the subjectshare is the realization that connection setup is a very time consuming task. Severalgroups have worked on methods for reducing the connection setup process.

In [9], Salonidis, Bhagwat and Tassiulas identify a number of bottlenecks inthe device discovery process and propose means of ameliorating the effects of thesebottlenecks by altering parameters in the protocol stack. Their calculations indicatethat a decrease in the expected connection setup time to almost half that of thecurrent specification is reasonable.

Busboom et al. [3] focus on unambiguous device identification, which mostly re-lates to security issues with Bluetooth, but the paper also mentions device discoveryand connection setup times on a theoretical level.

In [14], Welsh, Murphy and Frantz actually perform empirical tests of the devicediscovery and connection setup processes, albeit between personal computers withclass 1 Bluetooth, not between hand held terminals in motion with lower poweredclass 2 Bluetooth. The authors also explore changing parameters in the Bluetoothstack to speed up connection setup. They propose more changes than Salonidis etal., cutting setup times by about 75 %.

Finally, in [13] Tourrilhes describes the implementation of the Connection Diver-sity framework to allow TCP/IP applications run seamlessly on top of Bluetooth.Here too, some work was done to improve the setup performance, both by modifyingparameters in the Bluetooth stack and by adding caching features on top of it.

With the exception of [14], none of these articles cover real life performance, butrather focus on calculated theoretical performance.

This Master’s thesis should be of interest due to the fact that it covers perfor-mance with the type of Bluetooth devices built into mobile phones – an importantsubject in the field of mobile computing. The performance evaluation also focuseson short lived connections between moving devices that are set up without user in-teraction. This is a kind of ad-hoc use for Bluetooth which is very attractive froma mobile and pervasive computing viewpoint and that has been mentioned5 but notoften implemented.

5In particular, J. Haartsen mentions a number of usage scenarios for Bluetooth in [4] that requirequick connection setup to be convenient.

3

1.4 Method

Since the goals of this thesis project were of two fairly different kinds – evaluationand development – two methods were formulated. We decided that the evaluation,being the largest part of the project, should be carried out first. The early parts ofthe evaluation would also pave the way for the JNI library implementation.

The following method for the evaluation part of the project was decided upon:

1. Develop a testing application.

2. Decide on evaluation scenarios.

3. Perform evaluation.

4. Analyze collected data.

5. Draw conclusions and give recommendations..

Pure development is even more straightforward. We decided upon the followingmethod for developing the JNI library:

1. Design a suitable Java API.

2. Adapt the testing application to the Java API and write “glue” code.

3. Test the library to verify its functionality.

1.5 Project Plan

The two methods quite clearly suggested the following development milestones:

1. a simple application capable of detecting nearby Bluetooth devices,

2. client/server applications capable of finding each other and transmitting data,whilst keeping count of the amount of data transmitted,

3. a Java API for establishing connections and transmitting data with JNI mem-ber function signatures, along with its native implementation, based on thecode from milestone 2.

This seemed the most natural way to plan the project, as the performance eval-uation relied entirely on the software being available. At the end of milestone 1,tentative tests regarding device detection time could commence, at the end of mile-stone 2, full performance testing could begin. With the data from the testing,conclusions could be made and the JNI development could commence.

4

1.6 Thesis Organization

This thesis is organized as follows: In chapter 2 we describe the hardware andsoftware environment in which the thesis project software runs. This includes adescription of the Bluetooth technology and a look at its theoretical performance.

Chapter 3 describes the different pieces of software developed during the courseof the thesis project. In particular, we take a look at how the operating system andthe limitations of JNI impacted the architecture and implementation of the thesisproject code. The development environments used are also discussed briefly.

In chapter 4, the test scenarios used to measure the performance of the Bluetoothhardware and software in the P800 terminal is described, along with the results anda discussion about our findings.

Chapter 5 holds our conclusions about the thesis project. We cover the challengesof implementing Bluetooth software on Symbian running on the P800 platform anddiscuss the implications of the performance tests.

Chapter 6 concludes the thesis with recommendations for work with Bluetoothsimilar to that which is done in the Mobile Services project. Some ideas for futuredevelopment and research are also presented.

5

Chapter 2

Hardware and Software Environment

In this chapter we describe the hardware and software foundation upon which theperformance tests of the Master’s project and the native bindings for Personal Javarun. We take a closer look at how Bluetooth works as well as how the Symbianoperating system API’s give access to Bluetooth. We also look at which Java virtualmachines are available on the P800 smart phone.

2.1 The P800 Smart Phone

The Sony Ericsson P800 smart phone was the main target for both the performanceevaluation and the JNI library. The P800 terminal is a GSM telephone with fullPDA capabilities. Features in the P800 that are of interest to us are that it runs theSymbian 7 operating system with UIQ1, has Bluetooth 1.1 support and support forboth Personal Java and MIDP (Mobile Information Device Profile) 1.02. Softwaredevelopment kits for C++ and the two Java variants are available free of chargefrom both Metrowerks and Borland.

While the device supports both Bluetooth and Java in the forms of Personal Javaand MIDP 1.0, The Java APIs do not support Bluetooth. The Symbian operatingsystem (OS) C++ APIs can be used to access the Bluetooth hardware, though,making it possible to write native bindings for Bluetooth for the Personal Javavirtual machine.

2.2 Bluetooth

Bluetooth is a short-range wireless radio technology for connecting devices and ex-changing data between them. Bluetooth operates in the license free frequency bandaround 2.45 GHz. Key features of Bluetooth are:

1UIQ is not an acronym, but the name of the user interface used in Symbian on the P800. Otherphone manufacturers may use other interfaces. See http://www.uiq.com/uiq

2MIDP 1.0 has been obsoleted by Sun, the latest version is 2.0. See http://developers.sun.com/techtopics/mobility/midp/index.html

6

• supports both voice and data

• communication between more than two devices possible

• does not require line-of-sight

• basic security with authentication and encryption

• small and cheap hardware

• low power consumption

• operates worldwide3

The idea for Bluetooth originates from a study made at Ericsson Mobile Commu-nications, but the Bluetooth standard was developed by the Bluetooth Consortium,formed by Ericsson, Intel, IBM, Nokia and Toshiba in 1998 [4].

Envisioned uses for Bluetooth were connecting mobile phones with computers,each other, hands-free kits, palmtop computers, printers and other devices. Devicesthat are connected using Bluetooth form a piconet. In every piconet one device is themaster and regulates traffic in that piconet. At most eight devices (one master andseven slaves) can participate in the same piconet, but one device can be a memberof more than one piconet. For example, it is possible for a device to have the masterrole in one piconet and participate as a slave in one or more other piconets. Nopiconet may have more than one master, however. A collection of piconets that areconnected by association through devices that participate in more than one piconetare called scatternets [4, 2].

In spite of the roles of master and slave, Bluetooth devices are in practice peers– they use identical hardware and software. Thus, while the device that initiatesa connection becomes the master of the established piconet, the role of master canbe transferred to a slave at a later time through the Role Switch Procedure [2], ifnecessary.

In theory, a Bluetooth connection can achieve data rates of up to 432.6 kbit/sin symmetric mode and 721/57.64 kbit/s in asymmetric mode [4]. The theoreticalrange of Bluetooth is 100 metres for class 1 Bluetooth and 10 metres for the lowerpower class 2 Bluetooth normally found in handheld devices. In reality, distancebetween peers, collisions, participation in more than one piconet and other factorslimit performance. Interference, walls and other structures impact both data ratesand range. Still, Bluetooth is a very useful medium for information transfer betweennearby devices and is built into most new mobile phones and many laptop and palm-top computers. Bluetooth connected headsets are commonplace and some computermanufacturers use Bluetooth to connect peripherals such as keyboards and mice tocomputers.

3In France, Spain and Japan, parts of this frequency band are reserved for military use. Blue-tooth will still function in these regions, but with fewer channels.

4in/out

7

2.2.1 Connection Setup in Bluetooth

On the device controller level, setting up a connection between two Bluetooth devicesis an asymmetric procedure involving two steps: “inquiry” and “page” [2]. In theinquiry step a device attempts to discover other Bluetooth devices in its vicinity.When a suitable device has been found, the page procedure is used to actuallyestablish a connection between the two devices. The active party in the connectionsetup is called the “sender” and will become the master of any piconet it forms. Thepassive party is called the “receiver”.

Sender Inquiry

A sender that wishes to establish a connection with a peer needs the address5 as wellas information about the native clock of the peer in question [3]. If this informationis not available, as is usually the case before forming a piconet, it has to be foundthrough the inquiry procedure.

A device performing an inquiry sends inquiry packets on 32 different wake-upcarrier frequencies in the Bluetooth frequency band. These frequencies are dividedin two 16 frequency trains, called A and B. The inquiring device hops trough all 16frequencies in a train every 10 ms. This is repeated 256 times (i.e. for 2.56 seconds)before frequency hopping on the other train is started. To find all nearby devices ina noise free environment the inquirer must alternate between train A and B at leastfour times. In other words, inquiry will take at most 10.24 seconds under favorableconditions [2].

Receiver Behaviour

Devices that are not performing inquiries and are not already participants in apiconet are in standby mode, periodically listening for inquiries [4].

In standby mode a listener hops through the wake-up carrier frequencies, lis-tening for senders, but at a much slower rate than the senders transmit. The hopsoccur at 1.28 second intervals and the receiver listens for 11.25 milliseconds on eachfrequency.

If the receiver intercepts an inquiry packet it backs off for a random amount oftime of 0 to 640 ms, then listening for another inquiry packet on the same frequency.The random backoff has the purpose of reducing the number of collisions amongreceivers. If a second inquiry packet is received after the backoff, the listener wakesup and responds with its address and clock information. If no second inquiry packetarrives, the devices goes back into standby mode.

If the receiver receives a page packet, it will wake up and initiate the connectionsetup procedure.

5Bluetooth hardware addresses, called Bluetooth Device Address (BDA), are globally unique 48bit entities [2].

8

Sender Page

When the sender has the address and clock information of a nearby device, it canpage said device, thereby waking it up and starting the connection setup procedure.A page is directed at a specific device, using an access code derived from the targetsaddress. Since the paging device knows the native clock from the inquiry process,the access code is sent on and around the time the target is expected to wake up,ensuring that it receives the page.

Under ideal conditions, the time needed for the page is uniformly distributedbetween 0 and 2.56 seconds, thus with an expectation of 1.28 seconds [3].

The connection setup process following a page can take much longer, in theoryas much as almost 5 hours [4], though such figures should be exceedingly rare inpractice.

2.2.2 Theoretical Performance of Connection Establishment

It is difficult to calculate an expectation for the whole inquiry-scan-setup process,since the time needed for inquiry depends on the number of devices present and thetime for the whole process depends on whether the inquiring device is allowed to findall nearby devices before starting a page. Nevertheless, figures on the time neededto establish a Bluetooth connection between two (or more) devices can be found indifferent articles. Some claim connection times of about 2 seconds between devicespreviously unknown to each other [8], others claim 4-12 seconds [13] and still othersreport typical setup times of 5.76 seconds and worst case times of 23 seconds [3].

Since the application for which Mobile Services intends to use Bluetooth is onewhere typically two (or possibly more) terminals need to connect and exchangeinformation and where any number of the involved terminals may be in motion,connection setup time is critical.

We do not expect the terminals in our application to move at high speeds, but apedestrian still may move at speeds of 1 to 2 m/s. Since the Bluetooth radios in theP800 terminal has a range of no more than 10 metres that means that two terminalsare in range for at most approximately 10 to 20 seconds, if one of the terminals isstationary. If both terminals are moving in opposite directions, the time availableshrinks to 5 to 10 seconds. (Terminals moving alongside each other in more or lessthe same direction are less of a problem, obviously, as they may stay in range ofeach other more or less indefinitely.) Even if connection setup time is in the lowerranges of the cited 2 to 24 seconds there might be preciously little time to performinformation transfer.

2.2.3 Theoretical Data Transfer Performance

In theory, a Bluetooth link between two “isolated” terminals (i.e. terminals thatdo not participate in more than one piconet) can transfer data at speeds of up to721 kilobits per second. The real-world transfer speed is obviously lower than thisand, as mentioned before, affected by amongst other things the distance between

9

the terminals, collisions and noise from nearby devices transmitting in the samefrequency band.

Given the minimum connection setup times cited in Section 2.2.2 above, in-range times of 5, 10 and 20 seconds and the maximum theoretical transfer speedof Bluetooth, calculating the maximum amounts of data theoretically transferablebetween two moving devices is simple. The results of such a calculation can be foundin Table 2.1.

Table 2.1. Theoretical data transfer figures (kbytes transferred).

Connection Setup2.0 s 4.0 s 5.76 s

In Range 5.0 s 270.4 90.1 0.0

10.0 s 721.0 540.8 382.1

20.0 s 1622.3 1442.0 1283.4

While these figures are purely theoretical and somewhat optimistic, they aregood enough for almost anything except very data-laden transfer tasks, such asmultimedia applications. It was our fear that connection setup times this low wereunrealistic on a handheld device.

2.3 The Symbian Operating System

The Symbian OS, previously named EPOC, is a preemptively multitasking, kernelbased operating system for personal digital assistants and mobile phones, written inC++. Symbian was designed to be modular and as memory and processor efficientas possible, while still using an object oriented API. Also, it was designed to run fromread-only memory [12]. These design considerations become visible when developingfor Symbian in C++.

2.4 The Symbian API

The native Symbian API is object oriented and written in and for C++. It coversall possible aspects of using a smart phone, but we focus on the two aspects of pro-gramming with the API that relate to using and writing JNI bindings for Bluetooth.These are the multitasking systems of the operating system and the Bluetooth APIitself.

2.4.1 Processes, Threads and Active Objects

Symbian provides three types of multitasking: processes, threads and active objects.Each process has its own virtual address space, translated to physical addresses bythe system’s memory management unit. This provides memory protection betweenprocesses, meaning that one process cannot directly access memory belonging to

10

another process. Each process has one or more threads that multitask preemptivelyin the process memory space. The operating system kernel handles scheduling ofthe threads. Threads are given execution time on a priority basis, with each threadhaving its own priority.

Context switching, i.e. the switching of execution from one thread to another,is relatively expensive in terms of processor time. The worst kind of context switchis between threads in different processes. Since processor time is typically scarce ondevices running Symbian, it is preferable to avoid context switching to the greatestextent possible. The Symbian OS therefore provides a fashion of multitasking thatdoes not require the spawning of more threads. This multitasking is accomplishedwith active objects. Active objects multitask in a non-preemptive fashion.

The basis of the non-preemptive multitasking of active objects is that each threadin Symbian has an active scheduler that handles events for the thread, and theexistence of asynchronous calls. These are function calls that return immediatelyafter issuing a request for a particular task to be performed. Such calls usually resultin other threads (often even in another process) performing the work. When the taskis done, an event is sent to the requesting thread. The design of the operating systemis such, however, that many subsystems are singletons, running in only one threadin the whole operating system, and usable by all applications through asynchronouscalls. The total number of processes, and, as a consequence, the total numberof context switches between processes, is that way kept to a minimum. Requesthandlers of this kind are often called “servers” in Symbian terminology. Furthermore,care has been taken to package subsystems that can or need to cooperate closelyinto a single process. As an example, nearly all communications-related servers inSymbian run as threads in the same process [12].

The relations between an active object and a request handler (server) is illus-trated in Figure 2.1.

Asynchronous Call (Issue Request)

(return)

Call

(return)

RunL()

Request Complete (return)

Thread Active Scheduler Active Object Server/Request Handler

Active Object Thread Server Thread

Time

Figure 2.1. An active object at work, as a message sequence chart. Dashed linesare returning calls.

11

Asynchronous calls always require a status flag as one of its parameters. Anactive object inherits from the class CActive, which has one virtual member function:RunL(). When a task requested by an asynchronous call completes, the status flagis set (according to the completion status of the task) by the server thread and therequesting thread is notified. The active scheduler of the thread in question identifiesthe active object in the thread that issued the request and calls its RunL() function.In this way, a single thread can have several background jobs running through theuse of active objects. The programmer must take care to make RunL() return asquickly as possible, as it is not preempted within the thread in any way. Also, asingle active object may only have one outstanding request at a time.

Active objects are an efficient method of reducing the number of context switchesin an application. The flip side is that the asynchronous nature of their operation isdifficult to wrap in synchronous calls. Some, but not all, asynchronous calls in theSymbian API have synchronous counterparts.

2.4.2 Using Bluetooth in Symbian

There are two programming interfaces to Bluetooth in Symbian: the Logical LinkControl and Adaptation Layer Protocol (L2CAP) and the RFCOMM protocol. Thelatter is simply a software layer that emulates RS232 serial communication on topof L2CAP. Since serial communication was desired for the MobiTip application, wedeal only with RFCOMM in this Master’s thesis.

From a programming perspective, the concepts of communication between twoBluetooth devices are not entirely dissimilar to those of using sockets to connectdevices over a TCP/IP network on any platform. The process of setting up a con-nection differs, however, due to the special nature of piconets, the architecture ofBluetooth protocol stacks and the Bluetooth specification.

One such difference is the ad-hoc nature of piconets; piconets are formed asneeded, and the set of reachable devices changes often. Therefore, many Bluetoothcommunication sessions start with a search for nearby devices, to see which peers areavailable for communication. This procedure is time consuming, so the Bluetoothstack caches the addresses of all recently found devices. This hopefully speeds updevice detection in subsequent searches (if they are performed before the cacheexpires).

Another important difference can be found in the “service” concept, which iscentral to Bluetooth communications but only present in regular TCP/IP socketprogramming in a very rudimentary sense. In essence, a TCP/IP client applicationconnects to a server on a port – a logical channel with a numerical identifier. Someport numbers are by convention associated with a specific type of application. Whenit comes to Bluetooth, port numbers are not associated application types in anyway – not even by loose convention. Instead each application has a unique identifier(often the application or service class identifier). When an application wishes tosupply a service over Bluetooth, i.e. act as a Bluetooth receiver, it registers itsidentifier in a database and thereby gets a unused port number for its own use.

12

Senders that wish to connect to a specific type of receiver application then querythe receiver device about which port is currently used for that application, using theapplication identifier as a key. This is done through the Service Discovery Protocol(SDP). A service discovery agent then translates the application identifier suppliedin the sender’s SDP request to the port that the corresponding receiver instance hasbeen assigned through lookups in the SDP database [5].

The third difference lies in the fact that Bluetooth has a security layer. Bluetoothis designed to be able to provide security at both the link layer and the applicationlayer. Both the link encryption and authentication require that two devices wishingto communicate must either “know” each other, having exchanged keys at someearlier time, or ask the user for permission to set up a link.

It is worth noting that this design conflicts with the Master’s project goals definedin Section 1.2, specifically the requirement of user interaction free communication.Fortunately, it is possible to communicate in unsecure mode, but some work isrequired to achieve this.

2.4.3 Connection Setup On the Sender

There are three ways of setting up a connection to another device using the SymbianAPI. Two of them involve using graphical user interfaces for device selection and thusrequire user interaction, disqualifying them from use in this Master’s project. Thisis unfortunate, since the method that is recommended in [5] is by far the easiestto use. In this method, all of the work of scanning for devices and querying theremote devices about their services is hidden behind a single function call. The thirdmethod, however, requires no user interaction. This is the procedure for connectionsetup we will describe in this section. The steps involved in setting up a connectionin this programmatical manner are the following:

1. Find nearby Bluetooth devices.

2. Retrieve service database entries for each device and identify devices withwanted services.

3. Connect to one such device.

Finding devices is a matter of a broadcast query, the underpinnings of which isdescribed in Section 2.2.1. In the Symbian Bluetooth API, the query calls returnonce for each peer found, making it possible to start processing a peer as soon as itis found.

A query call only yields (at most6) the address and name of the peer it finds.Even though it is possible to connect to a peer using only this information and a

6It is possible to perform other queries than the general broadcast. For example, just as in thecase of IP sockets, it is possible to find the address of a device with a specific name, or the name ofa device with a specific address. Neither of these is useful for finding new devices to communicatewith, however.

13

port number selected in advance, a well behaved Bluetooth application uses the SDPto select a port to connect on.

This is done by letting one or two classes implement notifier and visitor inter-faces7 specified for this purpose. An agent class8 encapsulates the functionality forretrieving SDP entries from another device. The class that implements the notifierinterface supplies the agent with the address of the peer to query as well as a searchpattern for locating the wanted service in the remote SDP database.

An asynchronous member function in the agent is called to start the query.Upon finding the first SDP database entry that matches the search pattern, theagent calls a callback specified in the notifier interface. The notifier can then usethe implementation of the visitor (which also uses asynchronous calls and callbacks)to visit the attributes of the newly retrieved SDP database entry and act on theinformation in it, perhaps connecting to it.

The procedure, starting with a call to the agent from the notifier, is illustratedin Figure 2.2.

Start Search

Query Remote

(return)

Attribute Found

(return)

(return)

Visit Values

(return)

Notifier AgentVisitor

Time

Figure 2.2. An SDP database query, as a message sequence chart. Dashed lines arereturning calls.

This asynchronous architecture is the only way to directly query a remote SDPdatabase in Symbian. The interfaces and classes have no synchronous counterpartsto their asynchronous calls.

Connecting to a remote device is more straightforward. Using a connection tothe Symbian socket server (one of the communication servers mentioned in Section2.4.1) it is possible to configure and open a socket object and use an address objectto connect to any nearby device in only a few lines of code. Opening a connectionto the socket server is a a matter of a single function call.

This three-step process of establishing a connection between two devices can bemade completely free of user interaction, given set criteria for selecting a device toconnect to.

7MSdpAgentNotifier and MSdpAttributeValueVisitor respectively.8CSdpAgent.

14

2.4.4 Connection Setup On the Receiver

A receiver is, from the programmer’s perspective, generally passive in the connectionsetup process. The procedure for setting up a receiver are the following:

1. Request a free port to use.

2. Create an SDP database entry for the service provided.

3. Wait for incoming connections.

The system socket server keeps track of which ports are assigned to differentapplications. When a connection to the socket server has been opened and a sockethas been initialized, the socket can be used to query the socket server for a free portnumber.

An SDP database entry is a tree of attributes [2], making it possible to describea service in much more detail than just its name. One thing commonly stored in anSDP entry for a Bluetooth service is the port used by the service.

The Symbian API provides classes that represent the nodes and leaves of theattribute tree of an entry, as well as the entry itself. The SDP database itself isaccessed through a system server. After opening a connection to this system server,it is possible to insert an entry for a service into the database. Care must betaken to remove the entry upon terminating the receiver application, in order notto advertise a service that is not being supplied. All calls to the local SDP databaseare synchronous.

The receiver accepts incoming connections by calling the Accept() member func-tion of a socket instance. This function is available both in synchronous and asyn-chronous versions, but both require another socket instance as a parameter. Theparameter socket instance is used to communicate with the next sender. This stepcan be repeated with new socket instances, to allow the receiver to act as such formore than one sender.

2.4.5 Data Exchange

Once a Bluetooth connection has been set up, data exchange is simple. The socketinstances created on both sides of the connection have member functions for readinginto and writing from byte buffers. Both asynchronous and synchronous versions ofthese functions are available.

2.5 Personal Java

Personal Java is a Java Runtime Environment (JRE) version 1.1.6 with the cor-responding class library running on a small device. Personal Java is consideredobsolete by Sun, but it is available in many current handsets, including the SonyEricsson P800. The successor to Personal Java is MIDP9 Personal Profile which is a

9Mobile Information Device Profile, see http://java.sun.com/

15

Java 2 JRE. The main difference between Personal Java and MIDP Personal Profileis that support for JNI is voluntary in the latter.

On many modern handsets and personal digital assistants, Personal Java is beingphased out and replaced by MIDP 1.0 or 2.0. These MIDP versions have muchslimmed down versions of the Java API with device specific classes and calls as wellas a non-AWT10, non-Swing11 graphical user interface API. They have a sand-boxmodel making it impossible to write extensions that require native calls for it. Thisis not the case for Personal Java (and not necessarily the case for MIDP PersonalProfile) and it is fully possible to write native code (C and C++ in the SymbianCase) that is accessible to Personal Java applications through Java Native Interface(JNI) calls.

While some of the latest smart phone models from different manufacturers in-clude MIDP 2.0 and some of these even have MIDP API support their Bluetoothhardware, the P800 was not one of these models. Nor does the P800 support MIDPPersonal Profile.

2.6 The Java Native Interface

The Java Native Interface (JNI) is the standard interface for calling functions writtenin C from Java. The purpose of JNI is to allow programmers to use functionalityon different platforms that is not available in the Java API. JNI works the sameway on all platforms, though JNI itself is often used to make platform specificfunctionality available to Java programs. JNI also enables the use of Java objectsfrom C programs.

Creating JNI bindings for Java is, in theory, simple: define a Java class withsignatures for the methods to implement in C, declared as native. The JNI utilityprogram javah is then executed with the Java source file as input to generate a Cheader file with the necessary C function signatures.

By implementing the functions in the C header file in a source file that alsoimports the header jni.h a native implementation is created. The JNI header fileprovides access to predefined C data types that match the basic Java data types,including JObject, which represents Java objects and JClass that represents Javaclasses. It also provides a number of convenience functions for use with Java arrays,strings and other niceties present in Java but not generally in C. It is also possibleto use C++ for the native implementation, which is very convenient when using JNIon Symbian. The relations between the three layers in JNI is illustrated in Figure2.3.

Using Java objects and variables from C or C++ is a somewhat cumbersomeprocesses but the programmer has full access to all aspects of Java. This includesbreaking the rules, such as accessing the private members of any Java class or object

10Abstract Window Toolkit, the original graphical user interface library for Java.11The successor to AWT.

16

Native Class (C++) Native Class (C++) Native Class (C++)

JNI Functions (C/C++)

Java Class

Figure 2.3. The layers of JNI.

in the JRE. The convenience functions declared in the JNI header file also give someassistance.

The resulting native library is loaded into the Java class through the use of theSystem.loadLibrary() method.

2.6.1 JNI Limitations

While all of the above may seem straightforward enough, a number of factors com-plicate matters. JNI has its limitations, especially on the Symbian platform. Somethings are especially noticeable, such as the fact that it is difficult to cache referencesto Java objects on the native side. Other difficulties lie in Symbian’s limitation onlibraries and issues with processes and threads.

Since Symbian is designed to run from read-only memory (ROM), writable staticdata is not permitted in libraries [12]. This means that no library, such as a JNIlibrary, can directly hold references to native objects or variables between calls infile local variables (declared static in a C file). At first it seems that no state atall can be kept between native calls. Fortunately, there are two solutions to thisproblem, however convolute:

1. Use the single pointer per native thread that Symbian provides for this pur-pose, called the Thread Local Storage, to point to a heap allocated struct thatin turn contains references to all native objects holding state between calls.

2. Cast any pointers to heap allocated variables containing state informationto integers. These integers can then be passed to the Java Virtual Machinefor storage in the calling Java instance. In subsequent native calls, pass theintegers to the native function, where it can be re-cast to the right kind ofpointer and used there.

Furthermore, on every call to a native function, a pointer to the Java environmentis passed as a parameter. From the environment it is possible to extract pointersto Java objects. However, the environment pointer passed to native functions whencalled from Java are thread specific [6]. Caching references to the environment is

17

therefore not possible. Caching references to objects extracted from the environmentis possible by creating global references. (This is done through the use of specialfunctions included in JNI for this purpose). Still, when writing JNI code to becalled from threaded Java programs, the programmer must ensure that all nativecode is thread safe or that all Java code blocks that access the native functions aresynchronized.

Symbian threads running Java or JNI code also do not automatically have thethread active scheduler mentioned in Section 2.4.1, making the use of active objectsin the native implementation very difficult indeed [11]. Finally, not all peculiaritiesof threading and JNI are well documented. We will return to this specific problemin our account of the JNI library we implemented in Section 3.3.2.

Finally, there is the issue of memory management to contend with. Any java classthat has native methods must somehow ensure that any memory that is allocated(and not handed to the JRE for later garbage collection) in the native calls is freedwhen no longer needed. Since there are no destructors in Java objects, some kindof setup and shutdown methods are usually needed. A prime candidate for a setupmethod is obvious in many cases – every Java class that is intended to be instantiatedhas a constructor that is run when an instance is created. If all necessary memoryallocations in native code can be done when the Java object constructor is run,proper setup is silently enforced. There is no equivalent way to “force” the user ofan object with native calls to use a shutdown method, though. Fortunately, in manycases where one might want to introduce JNI bindings it is natural to manually shutdown instances. Input/output classes, in which it is common to use one methodto open a connection and another to flush buffers and close the connection, are anexample of such a case.

18

Chapter 3

Design and Implementation

The main implementation goal of the Master’s project was to create a library makingit possible to create Bluetooth links between P800 smart phones using nothing butPersonal Java. It was essential for the Mobile Services project that this could be donewithout need for end user interaction with the telephone. Moreover implementationof testing software to measure the performance of Bluetooth on the P800s had to bewritten.

In this chapter we first describe the development tools used, then go on to givean account of the general design of a Bluetooth application in Symbian. Finally wepresent reviews of the designs and implementations of the testing application andthe Bluetooth Java API along with its native implementation.

3.1 Development Environment

To develop for Symbian, one needs a software development kit (SDK) and a devel-opment environment of some kind. SDKs for Symbian are available free of chargefrom Symbian. There are two SDKs for UIQ, one tailored for the Metrowerks Code-Warrior integrated development environment (IDE), and one for the Borland C++Builder X IDE.

Both of these IDEs provide the same basic functionality. This includes some filemanagement for projects, front ends to their respective debuggers and the differentcompilers and linkers used to compile the source and resource files necessary for aSymbian program. The SDKs provide the headers, libraries, as well as compilersand linkers. The CodeWarrior SDK uses a proprietary compiler and linker, whilethe Borland SDK uses GCC1. Both SDKs also included EPOC emulators capable ofrunning Symbian 7.0 with UIQ 2.1. The Borland SDK required development toolsfrom Microsoft in order to generate binaries for the emulator it included.

Since Sics had purchased a license for the CodeWarrior IDE, development wasinitially done with this tool. The testing software was written using CodeWarrior.

1The GNU Compiler Collection, see http://gcc.gnu.org/

19

Two problems soon became apparent: First of all, the emulator would not recog-nize any USB Bluetooth adapter attached to the computer running the emulator,making it impossible for us to run any software using Bluetooth on the emulator.This meant that we had no way to run or debug most of our code on the emulator.

Second, on-device debugging using a P800 was not available in the version ofCodeWarrior we had access to. Thus, our only means of debugging was using on-screen messages and logging to a text file on the phone. Turnaround from codechanges through installing, running and transferring the log back to the computerwas cumbersome and typically took several minutes, making development more timeconsuming than anticipated.

When the development of the JNI library started it soon became apparent thatthe CodeWarrior SDK did not fully support JNI development. The build systemin the IDE did not generate function lookup code for the dynamic link library thatheld the native implementation. The Java runtime could therefore not use the IDE-compiled native code referenced in our Java API. Our installation of the CodeWarriorSDK command line build system was not capable of generating the lookup functionseither. Fortunately the Borland SDK command line build system could. At thatpoint we switched to using GNU Emacs and the Borland SDK for development, asetup that provided the base functionality needed for the rest of the developmentphase.

3.2 The Testing Application

In order to evaluate the performance of Bluetooth between P800s, we needed atesting application. This application had to be simple to use and capable of beingused as both a sender and a receiver. (Which we henceforth will refer to as the“client” and “server”, respectively.). To test Bluetooth performance, the applicationneeded to have functionality to connect to a peer and send and receive data sets ofour choosing, measuring the time used in doing so. We decided on a simple heuristicfor selecting which peer to connect to: let the client part of the application connectto the first peer announcing the “BTTransfer” service (the service name we chose forour application) it finds. When a connection has been established the client shouldsend the contents of a specific file on the device. The server part of the applicationwould accept connections, receive any data sent and write it to a specific file on thedevice. Both parts should report progress and time taken in their own log files.

The application also needed a simple user interface. In our case this consisted ofnothing more than a menu bar with commands for starting and stopping the serverand the client parts of the application and exiting the application altogether.

The testing application was written entirely in C++.

3.2.1 Design

We attempted to make the architecture of the testing software as simple as possible.Since the architecture of the SDP querying system is based on asynchronous calls and

20

predefined callbacks, as described in Section 2.4.3, it is natural to design a Bluetoothclient as a derivative of the active object class (see Section 2.4.1), using asynchronouscalls for this functionality as well. We also decided to reduce the complexity of thedesign by sacrificing some pureness in object orientation and create a single classthat implemented the entire client2. This was done by letting it not only inheritfrom the active object base class, but also, to enable SDP lookups, implement boththe necessary interfaces of the SDP lookup system.

The simplest possible server would use synchronous calls exclusively. In order toavoid the server blocking the user interface for long periods while waiting for incom-ing connections (thereby making the “stop server” command in the user interfaceunusable), we decided to implement the server as an active object, too.

Thus both the server and client classes are derived from CActive in order tomultitask as active objects. The client class also inherits from MSdpAgentNotifier

and MSdpAttributeValueVisitor in order to hold callbacks for traversal of servicerecords and handling of service record information. A complete class diagram forthe client and server classes and their parents can be seen in Figure 3.1.

CBase

CActive MSdpAttributeValueVisitor MSdpAgentNotifier

CBTTServer CServerFinder

Figure 3.1. Class diagram for the testing application client and server classes. TheCBase class is the base class for all instantiable classes in the Symbian API. Dashedlines indicate realization of an interface class, solid lines represent regular inheritance.

Both the server and the client classes have internal state machines. Their dif-ferent states correspond to different stages in the connection and data transfer pro-cedure. Transition between states normally occur when an asynchronous API callreturns, but there are exceptions to this rule, which are described in the next section.

3.2.2 Testing Application Runtime Behaviour

The main entry point of the client class is the ConnectRemoteL() member function,which starts the connection state machine. The server class state machine, on theother hand, is started by the class constructor. Hence, it only needs to be instan-tiated to start listening for and accepting incoming connections. We proceed by

2The graphical user interface for the testing application consisted of a number of classes gener-ated from stationary in the CodeWarrior IDE and of no real interest.

21

giving an account of the states and transitions in the state machines of the clientand server classes.

Client

EStateWaiting

EStateNotConnected EStateDiscovering EStateQueried

EStateConnecting

EStateQuerying

Figure 3.2. States In the Client Class. (Some transitions omitted for clarity.)

The states of the client class are shown in Figure 3.2. (In this figure, we have,for the sake of clarity, omitted transition arrows representing errors – it is possi-ble for the state machine to transit from any state to the EStateWaiting state.)A test run starts with a transition from the EStateNotConnected state to theEStateDiscovering state. Here, the application ensures that Bluetooth hardwareis available in the host device (if not, the application displays an error), whereupona search for nearby devices is started. As soon as a peer is found, a transitionto the EStateQuerying state is made. In this state, the client queries the remotedevice’s SDP database. If the peer is a server for the “BTTransfer” service, thestate machine proceeds to the EStateQueried state. If not, a transition back tothe EStateDiscovering state is made and the next device is queried. If no morepeers have been found, we consider it an error and the state machine returns tothe EStateWaiting state. In the EStateQueried state the port number used by thenewly found server is recorded and the client starts connecting to the server and con-tinues to the EStateConnecting state. When the connection has been establishedthe client transmits the contents of a predefined file to the server. When this taskhas completed it goes into the EStateWaiting state. This state separates test runs.As we will see in Section 4.3, we performed a number of runs with each data set.In the EStateWaiting state the application increments a run counter. If the runcounter has reached a certain number, the application exits. If not the applicationsleeps for a predefined amount of time before returning to the EStateNotConnected

state.Any failure in the connection setup process or data transfer process results in a

cleanup routine being run and the state machine being reset to EStateWaiting.

Server

The states of the server class can be seen in Figure 3.3. A server session does not ter-minate automatically, but keeps accepting connections one at a time until manually

22

EStateCheckingBluetooth EStateRegisteringSecurity

EStateAcceptingConnectionsEStateReadingData

Figure 3.3. States In the Server Class

shut down. A session starts with the state machine in the EStateCheckingBluetoothstate. Here the application ensures that the Bluetooth hardware in the host deviceis available. An immediate transition to the EStateRegisteringSecurity stateis made if the hardware check is successful. In this state a series of calls aremade to disable link and application level security, to allow any other device toconnect to the server. Any errors up to this point will cause the server to resetcompletely. Success at this stage results in the state machine advancing to theEStateAcceptingConnections state and any later errors will only disconnect anyconnected client and return the state machine to this state. Here, the server waitsfor an incoming connection. When a client does connect, the server state advancesto EStateReadingData as it reads the data sent by the client and writes it to disk.When no more data can be read from the client socket, the server closes the socketand returns to listening for a connection in the EStateAcceptingConnections state.

The testing application only accepts one client at a time as no more was neededfor the performance evaluation and because this restriction resulted in a much sim-pler server.

3.3 The Java API

The Java Specification Request 82 (JSR-82) [1] is a complete specification of a JavaBluetooth API that has been implemented on several platforms. However, since allthat was required by the Mobile Services project was an easy to use API for serialcommunication, a new Java API was created for implementation in this Master’sproject.

The new Java Bluetooth API was designed while the testing application wasstill being written. It was implemented, complete with native calls to the BluezBluetooth stack3 on Linux, for use in the stationary parts of the service that theMobiTip application is part of. The Linux implementation also served as a testingplatform for the software written for the P800 phone. Using the same Java API

3See http://www.bluez.org/.

23

on both Linux and the P800 phone has the advantage of making it possible to testBluetooth enabled Java applications on a personal computer running Linux, ratherthan having to go through the procedure of packaging and installing the applicationon a phone for testing during development. This was a strong argument for havingonly one Java API, in spite of architectural differences between Symbian and theBluez Bluetooth stack that we used on Linux.

3.3.1 Design

The Java API and the Symbian implementation of it is illustrated as an entityrelationship diagram in Figure 3.4. Every entity in the diagram is a regular class,except SicsBtLib and BTSocket, which are abstract classes. To implement the APIfor a new architecture, these two classes must be extended. All native calls shouldnormally reside in the platform specific subclass of SicsBtLib.

BTSocket

BTDeviceSymbian

BTDevice

SicsBTLib

UUIDSDPRecord

BTSocketSymbian

SicsBtLibSymbian

Extends

*

*

1

*

Extends

Extends

*

1

Figure 3.4. The Java Bluetooth API as an entity relationship diagram.

The nexus of the API is the implementation of SicsBtLib, in the Symbian caseSicsBtLibSymbian. The methods of this class handle the following tasks:

1. Device setup using SDPRecord and UUID instances.

2. Searching for nearby devices, a call that returns an array of BTDevices.

3. Connecting to a server, which returns a platform specific implementation ofBTSocket.

4. Listening for and accepting incoming connections. This too results in a plat-form specific implementation of BTSocket being returned.

Transmitting or receiving data between devices is done with the BTSocket in-stances (BTSocketSymbian in the Symbian implementation) returned by the connect

24

and listen methods. This class has methods for reading and writing data in bytearray form, much like any other Java input/output class.

3.3.2 Underlying C++ Implementation

Initially it was our expectation that creating a JNI library would be a simple taskonce we had a working testing application. It turned out that limitations in Symbianand JNI (mentioned in Section 2.6.1) make it nontrivial to move code between a pureSymbian application and a JNI implementation. The major obstacle was the lackof an active scheduler in the thread in which the JNI library executes. Withoutan active scheduler the use of active objects becomes impossible. Also, the onlyreasonable solution for wrapping the SDP querying functionality of our testing clientinto synchronous methods in the Java API was using Java threads. We deemed thisto be too much work for a mere prototype and decided to exclude SDP functionalityfrom the prototype library in addition to modifying our native client and serverclasses so as not to inherit from CActive.

The JNI library prototype delivered to the Mobile Services project thus incorpo-rated two native classes, one server and one client, just like the testing application.Their functionality was, with the exception of the excluded SDP querying, the same,though completely synchronous. Unlike in the testing application this does not causeproblems with interface locking, since putting all calls to the Bluetooth library ina separate Java thread solves this problem. Without the SDP queries to determinewhich port to connect to the server on, we selected a port number predefined andhard coded it into the application.

It is possible to work around these problems by starting an active scheduler inthe Symbian thread that runs the asynchronous calls. This requires some work withthreads which is quite treacherous in combination with JNI. Some late experimen-tation indicates how this can be done. We will discuss this in Section 5.4.1.

25

Chapter 4

Bluetooth Performance Evaluation

In this chapter, we describe the tests we performed to evaluate the time needed forBluetooth connection setup between P800 terminals as well as between a P800 ter-minal and a hotspot. We also measured the amount of data transmittable during thetime the two parties were connected. We hoped that we could show that Bluetoothwould be a viable option for transmitting data between both stationary and movingdevices. The tests showed that this was the case, though not by a large margin.

4.1 Test Rationale

MobiTip, the final application of the Bluetooth Communications library written asa part of this Master’s project involves moving terminals occasionally meeting andcommunicating with each other. For our evaluation of the performance of Bluetoothbetween P800 telephones running MobiTip and between phones and hotspots, weconsidered the following scenarios:

1. Two stationary terminals near each other exchanging information, such as inthe case when two users eat at the same restaurant, at nearby tables.

2. One stationary terminal exchanging information with a passing terminal, asin the case with one user having a cup of coffee at a coffee bar, while anotheruser passes by.

3. Two terminals passing by each other exchanging information, typically occur-ring as two users walk past each other.

4. A terminal passing by a hotspot, whilst exchanging information.

5. Two terminals in motion near each other, sometimes going out of range, onlyto return in a short time. This might occur if two users randomly make theirway around in a small area, such as when browsing in a shop.

6. A stationary terminal communicating with a hotspot.

26

4.2 Test Scenarios

In order to capture the essence of these scenarios, the following tests were decidedupon:

1. Both terminals stationary.

2. One terminal stationary, one in motion, moving toward and past the other,one transfer attempt per pass-by.

3. One terminal stationary, the other roving around the area, transfer attemptsperformed with ten second intervals.

The relation between the first scenario and the first test is obvious. The secondand third tests match scenarios two, three, and to some extent scenario five. Wedecided to not perform any tests that match the fourth or last scenarios exactly. Wereasoned that the performance when transferring data between two terminals wouldbe a worst-case scenario for transfers between a hotspot and a terminal. Preliminarytests indicated that a computer is a much faster receiver than a terminal, probablydue to faster non-volatile storage. If a terminal becomes stationary near a hotspot,transfer speeds will most likely be at least equal to those found between stationaryterminals. The equivalent applies to communication between a moving terminal anda stationary hotspot. Thus, if the three tests indicated acceptable performance, itwould be safe to assume that performance in all scenarios would be acceptable.

We attempted to simulate the environment in which we expected the final prod-uct to operate, but further performance testing with a functioning version of Mo-biTip should be performed to gauge the usefulness of Bluetooth as a medium fordata transfer between P800 terminals in that specific application, using the Blue-tooth implementation in the Java library described in Section 3.3.

4.3 Test Setup

Performing tests in environments and under circumstances similar to those we ex-pected the final product to operate in would have been exceedingly difficult giventhe fact that project time constraints were also a limiting factor for the tests. Still,we wished to approximate the “live environment” as closely as possible with thesoftware and time at hand.

In all tests we measured the time needed to detect peers (inquiry) and the SDPquery time. The time needed to transfer data and hence the transfer data rate weremeasured separately for the client and server.

To test performance at different ranges, we performed tests where two phoneswere placed at different distances from each other. At first we considered the ranges1, 5, and 10 metres, the latter being the maximum advertised range of Bluetooth.While the phones used in the test were able to detect each other 10 metres apart itwas not possible to transfer any data. After experimenting with different distances

27

beyond 5 metres we decided on the 1, 5 and 7.5 metre ranges. We executed two testruns each on the 1 and 7.5 metre ranges and three test runs with devices 5 metresapart. Each test run consisted of 80 attempts at each range. In the 80 attempts, filesof the sizes 1 kbytes, 5 kbytes, 10 kbytes and 50 kbytes were transferred 20 timeseach.

In order to reduce connection setup times, Bluetooth stacks normally cache theidentities of nearby devices they have found. The Bluetooth stack in the P800 phoneprovides such caching. This is advantageous for devices that need to reconnect toeach other several times within a short time span. We did not expect MobiTip tohave much use for this feature though, meaning that caching would not represent ourusage scenarios. The P800 does not allow disabling of the cache, so to get realisticmeasurements we performed an overnight test run where we had introduced a tenminute delay between attempts to let the cache clear before scanning for devicesagain. In all other respects this test run was configured similarly to the ones alreadymentioned: 80 attempts on different file sizes as per above, terminals 5 metres apart.No retries were allowed.

In all test runs mentioned except one of the three at 5 metres we allowed the clientto retry a failed connection attempt up to 10 times. The 5 metre test without retrieswas made to see how much the retries affected the inquiry time and the number offailures. Also, the overnight cache free run never used any retries (though they wereallowed), making a test without retries but with cache interesting.

We also conducted two smaller tests with moving terminals. The first one con-sisted of walk-by’s, where a person holding a terminal started a test run ten metresfrom a stationary terminal, then walked past the stationary terminal to a distanceten metres beyond. The test run consisted of 20 attempts, each trying to transfer5 kbytes of data. No retries were allowed.

The second experiment with moving terminals involved one stationary terminaland a person holding another terminal and roving about the area randomly. Theroving party stayed within 10 metres of the stationary terminal at all times. Thiswas done while the roving terminal automatically attempted to connect to the im-mobile terminal to transfer 5 kbytes of data with 10 second intervals. Also this testcomprised 20 attempts with no retries.

Thus, in total, we attempted 800 connections under different conditions.

4.4 Results

The overall results from the tests with stationary terminals can be seen in Table4.1. The columns give the time to find a peer and SDP query time in seconds, thenumber of partial (incomplete) transfer and completely failed connection attempts,the transfer speed in bytes per second for the client and server respectively, and thenumber of connection attempts including retries. These results showed that the reli-ability of the Bluetooth was perhaps a bit lower than we had expected. On average10.5% (median 8.1 %) of the 640 connections failed partially or completely. Most of

28

Table 4.1. Overall Results. Bytes per second for client and server respectivly.The “Connects” column indicated how many attempts at establishing a connectionwere done, including retries. (Failed attempts have been removed from the meancalculations.)

Inquiry (s) SDP (s) Partial Failed Bytes/s Connects

1m Run 1 8.71 0.33 6 0 10710/9161 1271m Run 2 8.77 0.44 6 1 10980/9344 1355m Run 1 8.62 0.33 9 0 10430/8855 1285m Run 2 8.64 0.32 8 0 10880/9267 1285m Run 3 2.28 1.88 4 2 10970/8891 805m No Cache 2.28 1.87 2 4 10970/8891 807.5m Run 1 8.68 0.32 8 12 11600/9712 2167.5m Run 2 8.61 0.33 5 0 10930/9239 128

the failed connections occurred in the 7.5 metre tests, indicating that large distancesbetween devices affect the chances of succeeding with establishing a connection. Theaverage transfer speed of 78.5 kbit/s is lower even than the lowest maximum datarate of a symmetric link: 108.8 kbit/s [4].

4.4.1 Connection Setup

When looking at the connection setup process, we will only give result from theovernight test run, as that is the only test we performed that accurately reflects thetime needed to set up a connection to an unknown device. In all other tests, a newconnection would be attempted 10 seconds after the last connection had terminated.Due to the peer caching in the Bluetooth stack, rediscovery of the peer was muchfaster than one could reasonably expect in a real world situation. In fact, sometimesthe inquiry process for cached peers would happen so quickly that the millisecondresolution of the on device timer used to measure the elapsed time was too coarse tobe able to report the time elapsed. The times for inquiry in Table 4.1 do not reflectthis fact, however, since at least one attempt at every range took great amountsof time (sometimes over 2 minutes). The cause of this is uncertain, but allowingretries would seem to be a factor, considering the much lower inquiry figures of theretry free run at 5 metres (run 3). Not allowing retries increased the number offailed connection attempts. (Which we found in our preliminary tests, causing usto introduce the retries.) Therefore the data presented in Figure 4.1 is taken solelyfrom the overnight test run, in which the cache was allowed to expire before a newconnection was attempted.

We see that, apart from a spike of 13 seconds on attempt 35, the inquiry processtakes 2.25 seconds on average, with a median of 2.5 seconds. These numbers com-pare favourably to the statistical estimate of an expected connection set up time of2.88 seconds mentioned in [3]. The comparably large fluctuations (even when dis-regarding the spike) are easily explained by the frequency hopping inquiry process

29

0 10 20 30 40 50 60 70 800

2

4

6

8

10

12

14

Attempts

Sec

onds

Connection Setup

0 10 20 30 40 50 60 70 800

2

4

6

8

10

12

14

Attempts

Sec

onds

SDP Query

Figure 4.1. Time to set up a connection and time to perform SDP query at 5 metres.

and the uniformly distributed [3] random backoff delay of 0.64 seconds.A fact to keep in mind here is that the overnight experiment had the best possible

conditions with little or no disturbance from the surroundings and only one nearbyBluetooth device.

When looking at the SDP query times, we note that there is not much fluctu-ation. The query times average 1.92 seconds. The low variance is not surprising –all SDP queries happen when the two parties are already connected and any largefluctuation should be explainable by poor external conditions, such as large amountsof interference and impenetrable obstacles between the client and the server. How-ever, looking at Table 2.1 we see that a two second difference in the total connectionsetup time makes a big difference when it comes to the amount of data that can beexchanged in a short lived piconet .

Statistics for the total connection setup time can be derived from the inquiryand SDP query figures. These are the results:

• Minimum time: 1.77 seconds.

• Median time: 2.82 seconds.

• Mean time: 4.22 seconds.

• Maximum time: 14.37 seconds.

30

We see that the observed connection setup time is clearly in the range of thetypical setup times of 2 to 5.76 seconds cited in Section 2.2.2, in spite of the factthat the observed mean setup time is exaggerated due to the spike in attempt 35.

When comparing the times above to those in Table 4.1, we see that most ofthe cached experiments were much slower than cache free tests. This may seemcontradictory, but is in fact not. The majority of tests were of the repeat-on-failuretype. We had introduced this behaviour to mitigate the frequent cases of incompletetransfers and the cases of transfers that returned an error code in spite of otherwiseappearing to complete successfully. When the testing application was allowed toreset a connection and try again on weaker grounds the failure rate fell, but thefrequent retries cause the connection setup time to increase. We see that all but thetwo retry-free 5 metre tests report well over 120 connection attempts, of which 80are original attempts and the rest are retries. Apparently over 50% of the connectionattempts require a retry.

4.4.2 Data Rates

Looking at the data rates, for which we have compiled means in Table 4.2, we noticetwo things: First of all the transfer speeds are low. The peak rate in this selectionis around 105 kbit/s. Granted, higher than the overall average, but still around 7times slower than the theoretical peak speed of 760 kbit/s.

Table 4.2. Mean data rates in bytes/second (total transfer time in seconds) at 1, 5and 7.5 metres. The figures in the table stem from 6 of the test runs with stationaryterminals with retries.

1 metre B/s (s) 5 metres B/s (s) 7.5 metres B/s (s)

5 kb Run 1 12639 (0.41) 12509 (0.41) 13149 (0.39)5 kb Run 2 13495 (0.38) 13152 (0.39) 13284 (0.39)10 kb Run 1 10322 (0.99) 9942 (1.04) 10304 (1.0)10 kb Run 2 10292 (1.0) 10263 (1.0) 10323 (0.99)50 kb Run 1 9178 (5.59) 8833 (5.80) 10985 (5.15)50 kb Run 2 9285 (5.51) 9225 (5.55) 9183 (5.58)

Secondly we notice that the data rate does not seem to degrade with greaterdistance between the terminals. This is contrary to what we had hypothesized. Wehad also hypothesized that transfer speeds would degrade with increasing amountof data to transfer, due to hardware factors on the receiving end; slow writing toFlash memory with buffers filling, slow processor handling the input/output, and soon. The latter, at least, does not seem impossible given the figures above, but therelatively high transfer speeds at 7.5 meters (beyond which we could hardly get thedevice to connect at all) is hard to explain. It is possible that the overall low datarates give us a hint – perhaps it is not that the transfer speeds at 7.5 meters arehigh, but that all the figures are low.

31

4.4.3 Moving Terminals

All of the above results pertain to stationary terminals only. A more realistic situ-ation is one where at least one of the terminals is in motion. As mentioned earlier,we did perform some such tests, but creating reproducible testing conditions is ex-tremely difficult for these scenarios. More work is clearly needed in this area. Onething that would be worth looking into is performing tests with moving terminalswhile bypassing the cache as we did in our overnight experiments. The fact that wecould not turn off the cache in the P800s used for the testing mean that we couldnot collect any meaningful data on the connection setup times for moving devices.We still went through with the two tests, however. The results can be summarizedas follows:

In the walk-by case, we recorded failure to connect at all in 9 cases and incompletedata transfer in 7 attempts. The total number of attempts was only 20, so thesenumbers were somewhat disappointing. We also noticed that the partial sends tookvery long time with a mean time of 24 seconds on all sends, median 29.4 seconds.This should be compared to the mean transfer time of the completed transmissions:6.625 seconds for the full data set of 50 kbytes. We believe this might have beencaused by the sender going out of range toward the end of the transmission. Thisindicates that some kind of timeout mechanism in both the sender and receiverwould be prudent.

The completely failed connects can perhaps be explained by the fact that a scanfor devices is not required to last longer than 10.24 seconds [14]. If the sender andreceiver are hopping on the same frequency at the start of the walk-by, it is possiblethat they are out of range precisely when they would otherwise have detected eachother. By the time their frequency hopping is in-phase again, the sender may alreadyhave passed out of range again or stopped transmitting altogether.

In the case of the roving terminal, the failure rate was much lower. We recordedno complete failures of the 20 attempts, and only one incomplete transmission. Themean time used to transfer the 50 kbyte data file was 9.02 seconds. The variancewas large, with an 8 second span between the fastest and slowest transmission. Thegraph in Figure 4.2 illustrates this fact.

It should be mentioned that while it was not possible to keep exact track ofthe distance between the two terminals during the roving test, they were probablyseldom the full 10 metres distant from each other. Perhaps this was also a factor inthe improved connectivity compare to the walk-by test.

4.5 Discussion

Setting up a connection between two Bluetooth devices appears to be fast as long asthe endpoints are stationary and in an open, relatively disturbance free environment.When one of the terminals is in motion, and hence most likely also when bothterminals are in motion, link formation is not quite as quick as one might wish.In the scenario with devices moving in and out of range of each other, connection

32

0 2 4 6 8 10 12 14 16 18 200

2

4

6

8

10

12

14

16

18

Attempt

Sec

onds

Send Time

Figure 4.2. Time to send 50 kbytes of data between roving and stationary terminals.

setup appears to consume a large part of the time the devices are in range of eachother. It seems highly possible that this is the cause of the large number of failedtransmissions recorded when we tested this scenario. Some research has been doneon the topic of reducing connection setup time. For example, Salonidis et al. [9]note that

[. . . ] ad hoc networks may follow a repeating usage pattern of forming,performing a service and then disconnecting. In these scenarios, forma-tion of links between the nodes can often be a dominant component of theend to end delay.

The authors discuss modifying the connection establishment protocol used inBluetooth. In [14], Welsh et al. discuss the possibility of adding a “mobility mode”to the Bluetooth standard, one where a number of changes to the connection setupprotocol would decrease the time needed for connection setup.

Both these papers discuss altering the Bluetooth stack (and possibly breakingconformity with the current Bluetooth specification) to reduce connection setuptimes. At any rate, modifying parameters in the Bluetooth stack is not an optionwhen writing end-user applications. There is another method of reducing the con-nection setup times, however. We noted that the SDP query procedure used around2 seconds of the connection setup time in the cache free tests. If this factor could be

33

removed, Bluetooth appears to become a much more attractive mediator of infor-mation in short-lived networks. The SDP query time is a factor even in the cachedtests. For example, in the roving terminal test, SDP queries took on average 1.2seconds. The stationary tests had less overhead for SDP queries with means wellunder a second. But even if only a cache update check is removed the cache free andmobile scenarios would benefit. This could be accomplished by trying to connecton a predefined port instead of using SDP. Another method would be keeping trackof devices previously encountered and the port they used for the wanted service, ifthey provided it.

The cache caused more problems during the testing than letting a client reconnectto a server faster than likely in the real world. In a couple of our tests the client hadcached host entries for devices that were no longer in range when the test begun.This caused the client to try to contact these hosts in vain, in turn making the timeneeded to find and connect to a valid and present server skyrocket. It is necessaryto find a mechanism to either turn off the cache entirely in the final application, orto manually cache the addresses of hosts that do not run the server. That way itwould be possible to avoid trying to connect to them on subsequent searches.

Before we started our formal testing, all our attempts at overnight tests failedafter the first transfer. The asynchronous call we made to find nearby hosts wassomehow considered completed by the operating system, but a later sanity checkin the code indicated that the request was still marked as outstanding. With thiserror condition, the connection was aborted. This error was reproducible when thedelay between calls was above about one minute, but we are unsure whether it stemsfrom a bug or some aspect of Bluetooth programming we were unaware of. Settingthe delay between calls to 10 seconds allowed the program to work as intended, butsuch a short delay would not test the connection setup time without cache. To workaround this problem we used a synchronous call to find nearby hosts instead. Thisblocked the user interface from updating while the call completed, but allowed us toperform the tests. Still, our application crashed at times and we redid a few of thetest runs. It appears that the Bluetooth portions of the API have not been stresstested in any way similar to the way we used them. We have gotten the impressionthat less frequent use of Bluetooth, preferably with an empty cache, seems morestable than continuous on-off use of the subsystem. The large number of retries inthe stationary tests also lend some support to this suspicion.

When it comes to the transfer speeds we can only conclude that the numberswe have observed are very poor compared to the theoretical figures and much lowerthan we had expected. Transfer speeds also seem to vary greatly, especially in themoving test cases. This makes it hard to make any predictions about how muchdata really will be possible to transfer in a user-to-user session with MobiTip. Thishas caused some concern for the Mobile Service project. Then again, the interfaceto the Bluetooth stack that was used in the testing application was RFCOMM,which is a high level protocol. With the expenditure of some effort, it is possible tomodify the software to use the Logical Link Control and Adaption Protocol (L2CAP)instead. Since RFCOMM is built on top of L2CAP, it stands to reason that L2CAP

34

should at the very least not be slower than RFCOMM. As mentioned, the overall lowtransfer speeds may be the reason that our hypothesis about range being a factor intransmission capacity did not hold. Modifying the testing application to use L2CAPinstead of RFCOMM could provide insights into this matter.

Our other hypothesis, that the size of the data set to transmit affects the recordeddata rate seems to be more correct. If we are right about hardware capacity being thecause of the performance degradation, it seems likely that input/output performanceand computing power could become an issue for future mobile services. Testing thisaspect of the performance equation on a newer smart phone, such as the SonyEricsson P900 could help in verifying or dismissing this hypothesis.

A final topic for discussion is the one of energy consumption on smart phoneswith Bluetooth activated. No measurements of battery life when running the testingapplication were made, but there was no doubt about the fact that the applicationcaused an extra drain on the batteries of the P800. The MobiTip application shouldpreferably run at all times. Given the requirement that Bluetooth should be enabledand MobiTip should scan for peers from time to time, the battery life of a user’sterminal will most likely be nothing like it would be if MobiTip did not run. Aninvestigation into the possibilities of implementing power saving schemes for theMobiTip application might be in order, since users may be reluctant to use theservice at all times if this means considerably shorter standby time for his or hertelephone. Such power saving schemes must be clever enough to still allow forthe serendipity factor of two MobiTip user’s phones finding each other anywhere,anytime.

35

Chapter 5

Conclusions and Recommendations

In this chapter, we recapitulate the findings of our performance evaluation andassess how well the project goals have been met. We also present recommendationsbased on the evaluation performed as part of this Master’s thesis and offer a fewsuggestions for future work with the JNI library and introduce a couple of topics forfurther research.

5.1 Evaluation Results

The evaluation shows that while with a few caveats, Bluetooth is a viable medium forautomated communication between mobile phones in social services. It seems thatthe stability of the Bluetooth stack in the P800 and the data transfer performance arelarger problems than the connection setup time, which was initially thought to be thereal bottleneck in the Bluetooth communication. By foregoing the service databasequery during connection setup, that aspect of Bluetooth performance appears fullyacceptable.

In essence, the findings of this Master’s project were that while Bluetooth doesnot really seem to be built for the extremely short lived piconets envisioned forthe MobiTip application, it is still possible to use it in that capacity, and thatconnection setup was not the problem it seemed to be. Until some other, moresuitable technology arrives, it will be possible to implement social navigation inthe real world using Bluetooth as a carrier of social trails. Connections betweenterminals will most likely occur in cafés and restaurants more often than betweenpeople on the move, but are still possible.

During the course of this project a number of avenues for improvement of theprototype software have been identified. Several factors for consideration in thedevelopment of the MobiTip application have also been found. Examples of suchfactors are the transfer speed problem (which will most likely influence the designof other subsystems of MobiTip), a realistic figure for the range at which Bluetoothwill operate and the matter of high energy consumption when using Bluetooth.

36

With the recommendations in this chapter, the goal of evaluating Bluetooth forautomatic transfer of information between P800 terminals has been fulfilled.

5.2 Implementation

This Master’s project also produced one testing application for Bluetooth, runningon Symbian and written entirely in C++, and one prototype Java API with nativecalls and the requisite native Symbian library to support it. The testing applicationwas successfully used to perform the performance evaluation. The JNI library hasbeen tested and proven to work. Also, fully automated access to Bluetooth commu-nications was possible even with the prototype library that was produced. Overall,the implementation goals of the Master’s project were reached to such an extentthat they must be considered fulfilled. The JNI library has already seen further de-velopment and will hopefully become part of a functional prototype of the MobiTipapplication during the summer of 2004.

The JNI library has been released as open source under the BSD license and will,if possible, be made available to the public through the Sourceforge website1. It hasalso been delivered to Sony Ericsson, for possible publication on the Sony EricssonDeveloper Community website.

5.3 The Performance Requirement

The two aspects of performance found to be the most lacking in Bluetooth are thetime needed for connection setup and the data transfer speeds. The former hasbeen shown to be better than expected. It has also been shown that it can beimproved even more by ignoring the SDP and using predefined ports and settingsinstead. Judging from the performance evaluation, such a measure can in some caseshalve the time needed to set up a Bluetooth connection between two devices. Asit happens, the JNI library prototype does not support SDP. We recommend thatSDP is not implemented in the library and that a system for setting, reading andstoring settings for the library is implemented instead.

Transfer speeds have a large impact on a system using Bluetooth to form short-lived networks for information exchange. Reduction of the time needed to form aconnection will ameliorate the effects of having limited data transfer capabilities.Still, since there is at least one way to attempt to improve the performance of theJNI library, namely by moving from RFCOMM to L2CAP, we recommend doing so.

5.4 Future Work

This Master’s project has given rise to several ideas for future work, both in termsof further development of the Java Bluetooth API and research subjects.

1See http://www.sourceforge.net/

37

5.4.1 Further JNI Development

The JNI library prototype suffered from two shortcomings when it went out of thisMaster’s project’s scope. The first was that in was completely synchronous. Thiswas caused by the problems with threading and using active objects described inSection 2.6.1 and Section 3.3.2. One consequence of this was that it was impossibleto interrupt a server socket that was waiting for connection, and the only way tocancel it was to shut down the entire application owning it. A solution to thisproblem has since been found and partially implemented. Without going into greatdetail, we will describe the method here.

The general idea is to use two threads. In the first thread, which we call theworker thread, an active scheduler is created and installed. Then the active objectto be used is created and tied to the active scheduler. Also, a reference to the currentthread (i.e. the worker thread) must be stored in the active object and a pointer tothe active object must be stored in the Java environment. Finally the scheduler isstarted with a call that does not return until the scheduler is shut down by a callfrom another thread.

The second thread, which we call the call thread, is the interface for using theactive object in the worker thread. By using the pointer to the active object thatwas previously stored in the Java environment in the course of setting up the workerthread, states in the active object can be set. It is not possible to make asynchro-nous calls using the active object features of the active object from the call thread.However, by setting the state of the active object (a simple integer) in the callthread and then notifying the worker thread that a request has been completed, theRunL() function of the active object can be caused to run in the worker thread. Byinterpreting the state set in the call thread, RunL() can then make different asyn-chronous calls based on which member function was called in the call thread. Sincethe execution of RunL() happens in the worker thread and this thread has an activescheduler, such asynchronous calls are possible.

With proper synchronization or the use of the observer pattern, it is possible tomake this process thread safe. The first limitation has thus been eliminated.

The second limitation was the incomplete implementation of the library’s han-dling of multiple clients. This should be looked into to allow the full 7 slaves tojoin a piconet mastered by the library. Most likely this problem has been greatlysimplified by the solution to the first problem.

5.4.2 Research Topics

During the course of the evaluation, we found several new research topics.One issue is that of the low transfer speeds and their exact cause. Is the hardware

a limiting factor, is it the platform or the choice of transport layer?Another interesting problem is that of the caching of peer addresses. The solution

we have touched upon is the possibility of adding another cache, holding addressesof hosts we do not want to know about. How to implement something like this andat what level are two more questions to answer.

38

The final research topic we present here concerns the energy requirements ofan application that uses Bluetooth extensively. The problem is the following: howoften should a Bluetooth client search for servers in order to maximize the chanceof finding one, while still keeping energy expenditure at a minimum? It is probablypossible make some kind of statistical calculation to answer part of this question.But then there is the possibility of using social trails to determine when and whereto use more energy and when to conserve it. In this way one could devise a systemthat uses the data it supplies to its users to “empower” itself.

39

References

[1] Java APIs for Bluetooth Wireless Technology (JSR-82) Specification Version1.0a. Web, April 2002. http://jcp.org/en/jsr/detail?id=82.

[2] Specification of the Bluetooth System Version 1.2. Web, November 2003.http://www.bluetooth.org/.

[3] A. Busboom, I. Herwono, M. Schuba, and G. Zavagli. Unambiguous deviceidentification and fast connection setup in bluetooth. In Proceedings of theEuropean Wireless 2002, Florence, Italy, February 2002.

[4] J. Haartsen. Bluetooth – the universal radio interface for ad hoc, wirelessconnectivity. Ericsson Review, (3):110–117, 1998.

[5] M. J. Jipping. Symbian OS Communications Programming. Wiley, 2002.

[6] Sun Microsystems. Java Native Interface 1.1 Specification. Web, ReferencedMay 2004. http://java.sun.com/j2se/1.4.2/docs/guide/jni/.

[7] Gy. Miklós, A. Rácz, Z. Turányi, A. Valkó, and P. Johansson. Performanceaspects of bluetooth scatternet formation. In Proceedings of the 1st ACM inter-national symposium on Mobile ad hoc networking & computing, pages 147–148.IEEE Press, 2000.

[8] R. Nüsser and R. Pelz. Bluetooth-based wireless connectivity in an automotiveenvironment. In IEEE Vehicular Technology Conference, pages 1935–1942, Fall2000.

[9] T. Salonidis, P. Bhagwat, and L. Tassiulas. Proximity awareness and fast con-nection establishment in bluetooth. In Proceedings of the 1st ACM interna-tional symposium on Mobile ad hoc networking & computing, pages 141–142.IEEE Press, 2000.

[10] M. Svensson. Defining, Designing and Evaluating Social Navigation. PhD the-sis, Stockholm University/Royal Institute of Technology, 2002. ISBN 91-7265-573-9.

[11] Symbian. Symbian Developer Library. Web, Referenced May 2004.http://www.symbian.com/developer/techlib/sdl.html.

40

[12] M. Tasker, J. Allin, J. Dixon, J. Forrest, M. Heath, T. Richardson, andM. Shackman. Professional Symbian Programming. Wrox, 2000.

[13] J. Tourrilhes. On-Demand BlueTooth: Experience integrating BlueTooth inConnection Diversity. Technical report, Mobile and Media Systems Labora-tory, HP Laboratories Palo Alto, March 2003.

[14] E. Welsh, P. Murphy, and P. Frantz. Improving connection times for bluetoothdevices in mobile environments. In International Conference on Fundamentalsof Electronics Communications and Computer Sciences (ICFS), March 2002.

41

42

Appendix A

Glossary

Table A.1. Terms and Acronyms.

API Application Programming Interface.

AWT Abstract Windowing Toolkit.

BDA Bluetooth Device Address.

BSD Berkeley Software Distribution.

EPOC An older name for the Symbian OS.

GSM Global System for Mobile Communications.

IDE Integrated Development Environment.

JNI Java Native Interface.

JRE Java Runtime Environment.

JSR-82 Java Specification Request – Java APIs for Bluetooth.

JVM Java Virtual Machine.

L2CAP Logical Link Control and Adaptation Protocol.

MIDP Mobile Information Device Profile.

PDA Personal Digital Assistant.

Piconet A network of Bluetooth devices.

RFCOMM An RS232 serial cable emulation layer, built on top ofL2CAP.

Scatternet A network consisting of interconnected piconets.

SDK Software Development Kit.

SDP Service Discovery Protocol.

TCP/IP Transmission Control Protocol/Internet Protocol.

UIQ Not an acronym, but the name of the graphical user in-terface used by Sony Ericsson in their Symbian phones.

UUID Universally Unique Identifier.

43