By Bruce Hopkins 07/27/2004 You're A Java Developer, And You've Finally Got Yourself A Bluetooth Device. Maybe It's A Cell Phone, A PDA, OR A USB Dongle For Your Pc. or Perhaps You've Heard A lot about Bluetooth, but you are not sure what exactly you can do with it. In either case, you've had some exposure to Bluetooth, and now you're ready to start flexing your programming muscles with the technology. Great! The purpose of this article is to give you a good introduction to the Bluetooth protocol, including an overview of its protocol layers and profiles. We'll also cover the the classes and methods of JSR-82, the official Java Bluetooth API. Finally, we 'll wrap things up by describing what software That You'll Need in Order To Get Started.
What is bluetooth?
What exactly is Bluetooth? Well, simply stated, Bluetooth is a wireless communication protocol. Since it's a communication protocol, you can use Bluetooth to communicate to other Bluetooth-enabled devices. In this sense, Bluetooth is like any other communication protocol that you use . every day, such as HTTP, FTP, SMTP, or IMAP Bluetooth has a client-server architecture; the one that initiates the connection is the client, and the one who receives the connection is the server Bluetooth is a great protocol for wireless. Communication Because It's Capable of Transmitting Data At Nearly 1mb / s, while consuming 1 / 100th of the power of wi-fi.
In order for Bluetooth devices to communicate properly, they all need to conform to the Bluetooth specification. The Bluetooth specification, like any other spec, defines the standard that a Bluetooth device should adhere to, as well as rules that need to be enforced when communicating You can Download The Specification Documents At The Official Bluetooth Web Site. The Bluetooth Protocol Stack and Profiles Together Comprise The Bluetooth Specification.The Bluetooth Protocol Stack
The Bluetooth stack is the software or firmware component that has direct access to the Bluetooth device. It has control over things such as device settings, communication parameters, and power levels for the Bluetooth device. The stack itself consists of layers, and each layer of the stack has a specific task in the overall functionality of the Bluetooth device. Since Bluetooth device manufacturers are not required to use all of the layers in the stack, we're only going to cover the main ones that are implemented in almost every Bluetooth device .
HCI is the Host Controller Interface. This layer is the interface between the radio and the host computer. L2CAP stands for Logical Link Controller Adaptation Protocol. This layer is the multiplexer of all data passing through the unit. Audio signals, however, have direct access to the HCI. SDP is the Service Discovery Protocol. The SDP layer is used to find services on remote Bluetooth devices. RFCOMM is widely known as the virtual serial port protocol. OBEX is the object exchange protocol.
Bluetooth Profiles
Bluetooth Profiles were created to allow different Bluetooth devices to interoperate. For instance, let's say that you own a Bluetooth-enabled PDA and a Bluetooth-enabled wireless phone. Both devices have Bluetooth stacks. How can you tell if those two devices will allow you to synchronize the phone lists between each other? How will you know if you can send a phone number from the PDA to the phone? And most importantly, how can you determine if these devices will allow you to browse the Internet from the PDA, using the phone as a wireless modem? A Bluetooth profile is a designed set of functionality for Bluetooth devices. for instance, using the examples listed above, the phone and the PDA must both support the Synchronization Profile in order to synchronize data between them. in order To Send Object Data Such As a .vcf File from The Pda To The Phone, The Object Push Profile Implement. Finally, The Pda and The Wireless Phone Must Both Support The Dialup . Networking Profile in order for the PDA to wirelessly browse the Internet via the phone If you want your Bluetooth-enabled devices to interact, having a Bluetooth stack is not good enough - they also need to conform to a particular profile.
A word of caution here: do not get Bluetooth profiles confused with J2ME profiles J2ME profiles are a set of Java classes that extend the functionality of a J2ME Configuration For instance, the MID Profile is a set of Java classes that extend the functionality of.. the Connected Limited Device Configuration. On the other hand, a Bluetooth profile can be implemented in any language and on any platform, because it refers to a defined set of functionality for a Bluetooth-enabled device. So the Object Push Profile can be implemented on a Palm OS PDA in C , and can be implemented on a Bluetooth-enabled printer in assembly language. For those of you who are familiar with RUP methodology, Bluetooth Profiles are also called Bluetooth Use Cases.Java Bluetooth Application Concepts
The Basic Concepts of Any Bluetooth Application (Java Or OtherWise) Consist of the Following Components:
Stack Initialization DISCOVERY Device Management Service Discovery Communication
The Java Bluetooth Specification Adds a Special Component to the Mix Called The Bluetooth Control Center (BCC), Which is outside of the scope of this article.
Stack Initialization
Before you can do anything, you need to initialize your stack. Remember, the stack is the piece of software (or firmware) that controls your Bluetooth device. Stack initialization can consist of a number of things, but its main purpose is to get the Bluetooth Device Ready To Start Wireless Communication. Every Vendor Handles Stack Initialization Differently, So We'll Cover How To Initialize The Stack Using The Atinav Java Bluetooth SDK.
Importooth. *;
Import javax.microedition.io. *;
Import com.atinav.bcc;
Public Class WirelessDevice Implements DiscoveryListener {localDevice localdevice = null;
Public wirelessDevice () {
// setting the port number using atinav's bcc
BCC.SETPORTNAME ("COM1");
// setting the baud rate using atinav's bcc
Bcc.setbaudrate (57600);
// Connectable Mode Using Atinav's BCC
Bcc.setConnectable (TRUE);
// set discoverable model Using AtinaV's BCC
Bcc.SetDiscoverable (DiscoveryAgent.giac);
Try {
LocalDevice = localdevice.getloaclDevice ();
}
Catch (BluetoothStateException Exp) {
}
// Implementation of Methods in DiscoveryListener Class
// of javax.bluetooth goes here
// Now do some work
}
}
Device Management
LocalDevice and RemoteDevice are the two main classes in the Java Bluetooth Specification that allow you to perform Device Management. These classes give you the ability to query statistical information about your own Bluetooth device (LocalDevice) and information on the devices in the area (RemoteDevice) . The static method LocalDevice.getLocalDevice () returns an instantiated LocalDevice object for you to use. In order to get the unique address of your Bluetooth radio, just call getBluetoothAddress () on your local device object. The Bluetooth address serves the same purpose of the MAC address on the network card of your computer;. every Bluetooth device has a unique address If you want other Bluetooth devices in the area to find you, then call the setDiscoverable () method in LocalDevice object.
. In a nutshell, that's about all it takes to perform Device Management with the Java Bluetooth Specification APIs Now, let's take a look at the concept in Bluetooth that allows you to discover other Bluetooth devices: device discovery.
Device Discovery
Your Bluetooth device has no idea of what other Bluetooth devices are in the area. Perhaps there are laptops, desktops, printers, mobile phones, or PDAs in the area. Who knows? The possibilities are endless. In order to find out, your Bluetooth device will use the Device Discovery classes that are provided into the Java Bluetooth API in order to see what's out there.Let's take a look at the two classes needed in order for your Bluetooth device to discover remote Bluetooth devices in the area: DiscoveryAgent and DiscoveryListener .
After getting a localdevice object, Just Instantiate a DiscoveryAgent by calling localdevice.getdiscoveryAgent ().
LocalDevice local.getLocalDevice ();
DiscoveryAgent DiscoveryAgent = localdevice.getdiscoveryAgent ();
The are multiple ways to discover remote Bluetooth devices, but to be brief, I'll just show you one particular way. First, your object must implement the DiscoveryListener interface. This interface works like any listener, so it'll notify you when an event happens. in this case, you'll be notified when Bluetooth devices are in the area. in order to start the discovery process, just call the startInquiry () method on your DiscoveryAgent. This method is non-blocking, so you are free To Do Other Things While You Wait for Other Bluetooth Devices to Be found.
When a Bluetooth device is found, the JVM will call the deviceDiscovered () method of the class that implemented the DiscoveryListener interface. This method will pass you a RemoteDevice object that represents the device discovered by the inquiry.
Service Discovery
Now that you know how to find other Bluetooth devices, it would be really nice to see what services that those devices offer. Of course, if the RemoteDevice is a printer, then you know that it can offer a printing service. But what if the RemoteDevice is a computer Would it readily come to mind that you can also print to a printer server that's where Service Discovery comes in you can never be sure what services a RemoteDevice may offer;??. Service Discovery allows you to find out what they are .
Service Discovery is just like Device Discovery in the sense that you use the DiscoveryAgent to do the "discovering." The searchServices () method of the DiscoveryAgent class allows you to search for services on a RemoteDevice. When services are found, the servicesDiscovered () will be called by the JVM if your object implemented the DiscoveryListener interface. This callback method also passes in a ServiceRecordobject that pertains to the service for which you searched. With a ServiceRecord in hand, you can do plenty of things, but you would most likely Would Want to Connect To The RemoteDevice Where this serviceRecord Originated:
String ConnectionURL = ServRecord [i] .getConnectionURL (0, FALSE);
Service Registration
Before a Bluetooth client device can use the Service Discovery on a Bluetooth server device, the Bluetooth server needs to register its services internally in the Service Discovery database (SDDB). That process is called Service Registration. This section will discuss what's involved for Service Registration For A Bluetooth Device, and I'll Also Give You a Rundown of The Classes Needed to Accomplish this.
Note: In a peer-to-peer application, such as a file transfer or chat application, be sure to remember that any device can act as the client or the server, so you'll need to incorporate that functionality (both client and server ) into your code in order to handle both scenarios of Service Discovery (ie, the client) and Service Registration (ie, the server). Here's a scenario of what's involved to get your service registered and stored in the SDDB.Call Connector.open () And Cast The Resulting Connection to A StreetConnectionNotifier.
Connector.open () creates a new ServiceRecord and sets some attributes. Use the LocalDevice object and the StreamConnectionNotifier to obtain the ServiceRecord that was created by the system. Add or modify the attributes in the ServiceRecord (optional). Use the StreamConnectionNotifier and call acceptAndOpen () And Wait for Bluetooth Clients to Discover This Service and Connect.
..........................
The System Removes The Service Record from The SDDB.
StreamConnectionNotifier and connection.
// lets name uriables
StreamConnectionNotifier Notifier = NULL;
StreamConnection sconn = NULL;
LocalDevice localDevice = null;
ServiceRecord serviceRecord = null;
// step # 1
// the string url will already be defined with the
// Correct URL Parameters
Notifier = (streamconnectionNotifier) Connector.Open (URL);
// step # 2
// We Will Get The LocalDevice If Not Already Done SOLOCALDEVICE = localdevice.getlocalDevice ();
ServiceRecord = localdevice.getRecord (Notifier);
// step # 3 is optional
// step # 4
// this Step Will Block The Current Thread Until
// aclient responds this Step Will Also Cause The THE
// service record to be stored in the sddb
Notifier.acceptandopen ();
// step # 5
// Just Wait ...
// Assume The Client Has Connected and You are Ready to EXIT
// step # 6
// this causes the service record to be removed
// from the sddb
Notifier.Close ();
AND That's all this you need to do service registration in blueooth. The next step is communication.
Communication
Bluetooth Is A Communication Protocol, SO How do you communicate with it? Well, The Java Bluetooth API Gives You Three Ways To send and received Data, But for Right Now, We'll Cover Only ONE OF THEM: RFCOMM.
Note: RFcomm is The Protocol Layer That The Serial Port Profile Uses in Order To Communicate, But The Swo Items Are Almost Always Used Synonymously.
Server Connections with the Serial Port Profile
.
// let's name uriables
StreamConnectionNotifier Notifier = NULL;
StreamConnection Con = NULL;
LocalDevice localDevice = null;
ServiceRecord serviceRecord = null;
InputStream INPUT;
OutputStream output;
// let's create a url what contains a uuid That
// Has a Very Low Change of Conflicting With Anything
String URL =
"btspp: // localhost: 0011233445566778899Aabbccddeeff; Name = serialconn
// let's open the connection with the url and
// Cast IT INTO A StreamConnectionNotifier
Notifier = (streamconnectionNotifier) Connector.Open (URL); // Block The Current Thread UnTil a Client Responds
Con = notifier.acceptandopen ();
// The Client Has Responded, So Open Some Streams
INPUT = con.openputstream ();
Output = con?openoutputstream ();
// now That The Streams Are Open, Send and
// Receive Some Data
For the most part, this looks like just about the same code used in Service Registration, and in fact, it is! Service Registration and Server Communication are both accomplished using the same lines of code. Here's a few items that I want to point out . The String url begins with btspp:.. // localhost :, which is required if you're going to use the Bluetooth Serial Port Profile Next comes the UUID part of the uRL, which is 00112233445566778899AABBCCDDEEFF This is simply a custom UUID that I Made Up for this service; I could Have Chosen Any String That Was Either 32 Bits or 128 Bits Long. Finally, We Have; Name = Serialconn In The Url String. I Could Have Left Off THIS Part, But I Want My Custom Service To Have a name, So The Actual Service Record in The SDDB HAS The FOLLOWING Entry:
ServiceName = SerialConn
.................... ..
Client Connections with The Serial Port Profile
ESTABLISHING A Connection With The Serial Port Profile for a J2ME Client Is Simple Because The Paradigm Hasn't Changed for J2ME I / O. You Simply Call Connector.Open ().
StreamConnection Con = (streamConnection) Connector.Open (URL);
You obtain the url String that is needed to connect to the device from the ServiceRecord object that you get from Service Discovery. Here's a more complete listing of code that will show you how a Serial Port Profile client makes a connection to a Serial Port Profile server .String ConnectionURL = ServicesRecord.getConnectionURL (0, FALSE);
Streamconnection Con = (streamConnection) Connector.Open (ConnectionURL);
What Does A SPP Client Connection URL LOOK LOKE? IF The Address of the Server IS 0001234567AB, The String That The SPP Client Would Look Something Like this:
BTSPP: // 0001234567AB: 3
. ..................
Java Bluetooth Development Kits
The most widely available development kit for Java Bluetooth applications is the J2ME Wireless Toolkit 2.2 from Sun. It incorporates a Bluetooth network simulator, and has support for OBEX. And best of all, it's free! The current version of the J2ME Wireless Toolkit is available On Windows Platforms.
If you're targeting JSR-82-enabled Nokia phones, such as the 6600, then you may also want to try out the Nokia Developer's Suite 2.1. Much like Sun's Wireless Toolkit, the Nokia Developer's Suite is free and it also includes a Bluetooth Network Simulator. The Nokia Developer's Suite Supports Windows and Linux Platforms.
Sonyericsson Also Makes A Free Developments Kit for ITS P900 Java Bluetooth-enabled Phone, Which Can Be Found At Their Developer Site.
Atinav makes one of the most comprehensive JSR-82 implementations and developer kits with support for J2ME CLDC, J2ME CDC, and J2SE devices. They support numerous RS-232, UART, USB, CF, and PCMCIA Bluetooth devices. Their solution is based on an all-Java stack, and their SDK includes the following profiles:! GAP, SDAP, SPP, OBEX, FTP, Sync, OPP, Fax, and Printing - whew They make the only JSR-82 implementation for the PocketPC platform, and also support Windows and Linux.Possio makes a JSR-82 development kit that complements their Java Bluetooth-enabled access point, the PX30. The PX30 is a Linux-based access point, and is powered by an Intel XScale processor. It includes Wi- Fi, Bluetooth, And The CDC Foundation Profile.
Rococo is famous for making the first Java Bluetooth Simulator, although they also make a Java Bluetooth developer kit for the Palm OS 4 platform The simulator is currently priced at $ 1000, and supports the following profiles:. GAP, SDAP, SPP, and GOEP.
Avetana Is A German Company That Makes The ONLY JSR-82 Implementation for the Mac OS X Platform. The Also Provide JSR-82 Implementations for Windows and Linux.
Summary
What have we learned here? Hopefully, you should have a good understanding of what Bluetooth is and how to use it. Before you start communicating to other Bluetooth devices, you need to discover the devices in your vicinity, and search for their services. After All of the preliminaries area out of the war, you can stop, WHETABED DEVICE IN YOURA, WHETHER IT'S RUNNING JAVA or Not.
With over one million Bluetooth-enabled devices shipping per week (that's right, one million devices per week), there's a lot of PDAs, cell phones, laptops, desktops, access points, cameras, keyboards, mice, printers, audio players, and Vehicles Out There for your Mobile Java apps to play with!