Home

Bluetooth for Java

image

Contents

1. fields static int INQUIRY COMPLETED static int INQUIRY ERROR static int INQUIRY TERMINATED static int SERVICE SEARCH COMPLETED static int SERVICE SEARCH DEVICE NOT REACHABLE static int SERVICE SEARCH ERROR static int SERVICE SEARCH NO RECORDS static int SERVICE SEARCH TERMINATED methods void deviceDiscovered RemoteDevice btDevice DeviceClass cod void inquiryCompleted int discType void servicesDiscovered int transID ServiceRecord servRecord void serviceSearchCompleted int transID int respCode Interface L2CAP Connection fields static int DEFAULT MTU static int MINIMUM MTU methods int getReceiveMTU int getTransmitMTU boolean ready int receive byte inBuf void send byte data Interface L2CAPConnectionNotifier method L2CAPConnection acceptAndOpen Class LocalDevice methods java lang String getBluetoothAddress DeviceClass getDeviceClass int getDiscoverable DiscoveryAgent getDiscoveryAgent java lang String getFriendlyName static LocalDevice getLocalDevice static java lang String getProperty java lang String property ServiceRecord getRecord javax microedition io Connection notifier boolean setDiscoverable int mode void updateRecord ServiceRecord srvRecord Class RemoteDevice constructor protected RemoteDevice
2. public void pauseApp public void destroyApp boolean unconditional public void commandAction Command c Displayable s if c exitCommand destroyApp false notifyDestroyed if c srchCommand try BCC setPortName COM1 BCC setBaudRate 57600 BCC setConnectable false BCC setDiscoverable DiscoveryAgent NOT_DISCOVERABLE LocalDevice localDevice LocalDevice getLocalDevice device new RemoteDevice 10 discoveryAgent localDevice getDiscoveryAgent discoveryAgent startInquiry DiscoveryAgent GIAC this catch BluetoothStateException btstateex btstateex printStackTrace try deviceLst new List Devices List IMPLICIT dev img deviceLst addCommand exitCommand srchCommand null srchCommand new Command Refresh Command SCR deviceLst addCommand srchCommand deviceLst setCommandListener this display setCurrent deviceLst r3 EN 1 System out printlin deviceLst getSelectedIndex j catch Exception e e printStackTrace if c List SELECT_COMMAND int index deviceLst getSelectedIndex do service search for device index int attrSet 100 UUID uuids new UUID 1 uuids 0 new UUID 9856 true services null int transId discoveryAgent searchServices attrSet uuids device i PiconetMID1let ServiceLst new List Serv
3. If the encrypt parameter is set to false or is not in the URL at all then the transmissions between the client server are not encrypted After the connection has been established both the server and the client can check to see if the transmission is encrypted by calling the isEncrypted method of the RemoteDevice class If all of this sounds really complex to you don t worry the encryption decryption process is all done behind the by your underlying JSR 82 implementation so you don t have to worry about ciphers keys and other cryptogra elements Security Example Now let s take a look at a practical demonstration of the security measures that are provided to us by Bluetooth and the JSR 82 In this example the client uses authentication and authorization over an L2CAP connection to send a simple message to the server Initially encryption is not enabled so that we can demonstrate how easily a third party can capture your wireless data transmissions if left unprotected When running the example we used some of the many features of Mobiwave BPA D10 Protocol Analyzer The BPA D10 is a noninstructive Bluetooth Protocol Analyzer that allows the realtime capturing logging decoding and displaying of the Bluetooth data transmissions The BPA D10 is capable of capturing protocol information over the air and relaying the data to a host desktop computer through an Ethernet connection This allows remote data logging and unlimited stor
4. System out printin The service record servRecord 0 record is null are found during a service search ides the array of services that have been found ServiceRecord servRecord store this record transID servRecord length di System out println After this if record null System out printin The Second try was null Cancel all the service searches that are presently being performed for int i 0 i lt transactionID length i if transactionID i 1 System out printin agent cancelServiceSearch transactionID i Called when a device discovery transaction is completed The lt code gt discType lt code gt will be INQUIRY_COMPLETED if the device discovery transactions ended normally INQUIRY_ERROR if the device discovery transaction failed to complete normally INQUIRY_TERMINATED if the device discovery transaction was canceled by calling DiscoveryAgent cancelInquiry public void inquiryCompleted int discType synchronized this try this notifyAll catch Exception e class SppServerProcess extends Thread the constructor SppServerProcess public void run StreamConnectionNotifier Server null try LocalDevice local LocalDevice getLocalDevice local setDiscoverable DiscoveryAgent GI
5. try try prepare a receiv length clientconn g data new byte lengt read in the data s length clientconn r System out printin R connected buffer etReceiveMTU h ent by the client method blocks eceive data eceived length bytes from client and immediately send it back on the same connection echo clientconn send data catch IOException e System out printin I0O l Exception e getMessage clientconn close catch IOException e System out printin IOException e getMessage Listing 10 2 shows the code for the L2CAPEchoClient Listing 10 2 L2CAPEchoClient java import java lang import java io import java util import javax microedition io import javax bluetooth public class L2CAPEchoClient implements DiscoveryListener object The DiscoveryAgent for the local Bluetooth device private DiscoveryAgent agent The max number of service searches that can occur at any one time private int maxServiceSearches 0 The number of service searches that are presently in progress private int serviceSearchCount Keeps track of the transaction IDs returned from searchServices private int transactionID The service record to an echo server that can reply to the message provided at the command line private ServiceRecord record
6. System out printin serial input stream open exception e System exit 0 Create a new SPP server object try server new SppServerProcess server start catch Exception e System out printin Failed to start Spp Server e System exit 0 the main loop runs forever However it can be stopped by terminating the KVM from the command line while true Create buffer to receive data from the serial port byte rxdata new byte 64 int rxlen 0 int data try read in as many bytes from the serial port as currently available but do not exceed the current buffer length The read method blocks but is periodically released by an InterruptedIOException in order to allow other things to happen meanwhile while true data ser_in read rxdata rxlen byte data rxlent if rxlen gt 64 data 1 break System out printin data received from serial port len rxlen catch InterruptedIOException e System out printin serial port receive timeout e catch Exception e System out printin serial port receive exception e Did we get any data from the serial port if rxlen gt 0 Do we have a Bluetooth connection already if bluetoothport null Do we have an OutputStream on the BT connection already if bt out null no then cre
7. public void printDataTransferCompleted PrintJobEvent pje System out printin Data delivered to printer successfully public void printJobCanceled PrintJobEvent pje System out printin The print job has been cancelled public void printJobCompleted PrintJobEvent pje System out printin The print job completed successfully public void printJobFailed PrintJobEvent pje System out printin The document failed to print public void printJobNoMoreEvents PrintJobEvent pje System out printin No more events to deliver public void printJobRequiresAttention PrintJobEvent pje System out printin Some thing terrible happened which requires attention public class JPSBluetoothPrint implements Runnable L2CAPConnection 12capConn null private int maxRecv 1 private boolean printFile String fileName throws FileNotFoundException System out printin Invoking Common printAPI for printing file fileName PrintStatus status new PrintStatus Create the DocFlavor for GIF DocFlavor flavor DocFlavor INPUT_STREAM GIF Create an attribute set comprised of the print instructions PrintRequestAttributeSet attribSet new HashPrintRequestAttributeSet attribSet add new Copies 1 attribSet add MediaSizeName ISO A4 Locate print services which can print a GIF in the manner
8. Keeps track of the devices found during an inquiry private Vector deviceList The constructor creates an L2CAPEchoClient object and prepares the for device discovery and service searching public L2CAPEchoClient throws BluetoothStateException Retrieve the local Bluetooth device object ocalDevice local LocalDevice getLocalDevice Retrieve the DiscoveryAgent object that allows us to perform device and service discovery agent local getDiscoveryAgent Retrieve the max number of concurrent service searches that can exist at any one time try maxServiceSearches Integer parseInt LocalDevice getProperty bluetooth sd trans max catch NumberFormatException e System out printin General Application Error System out printin NumberFormatException e getMessage transactionID new int maxServiceSearches Initialize the transaction list for int i 0 i lt maxServiceSearches i transactionID i 1 record null deviceList new Vector Adds the transaction table with the transaction ID provided private void addToTransactionTable int trans for int i 0 i lt transactionID length i if transactionID i 1 transactionID i trans return Removes the transaction from the transaction ID table private void removeFromTransactionTable in
9. Package com ericsson blipnet api event Methods boolean equals java lang Object obj Returns true if content of object is equal to this int getBytesCompleted Returns the number of bytes received so far java lang String getObexName Returns the name of the OBEX object to which this event is related int getObjectSize Returns the total size of the object to which this event is related BluetoothAddress getTerminalID Returns the Bluetooth device address of the terminal to which this event is related int hashCode Interface ObexProgressListener public interface ObexProgressListener This abstract class should be extended to create an event listener for listening to ObexProgress while pushing content to a terminal Package com ericsson blipnet api event Methods void newProgress ObexProgressEvent e This method is called by the BlipServer whenever new push progress information is available Events Interface ObexPushObject public interface ObexPushObject extends java io Serializable TheobexPushObject class defines a common interface for OBEX objects which are going to be pushed to a terminal Package com ericsson blipnet api obex pushobjects Methods byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String getObexType Returns the mime type of this ObexPu
10. In the wireless communication arena there is no technology that is best suited for every possible application Either Bluetooth or 802 1 1b can be used for wireless communication between computers Both have their place in the market and can perform in their niches well Newer wireless LAN protocols like 802 11a and 802 11g will further clear the distinction between Bluetooth and wireless LAN because they extend 802 11b s bandwidth limitation to 54 Mb s Bluetooth Devices on the Market Today Now let s take a look at Bluetooth devices that you can get at any consumer electronics store today We ll highlight the problems that Bluetooth solves and give some scenarios for using this technology If you re already familiar with common usage scenarios of Bluetooth devices then feel free to skip this section Wireless Data Transfer PDA to Phone Almost everyone owns a mobile phone nowadays These devices are very convenient compact and cute well at least some of them However they suffer from two major limitations Mobile phones have limited memory for phone book entries Data entry on mobile phones can be cumbersome We ve all been there before Entering data on a mobile phone is very tedious because you re dealing with a nine button keypad to type alphanumeric text Also mobile phones don t have a lot of memory for storage so you re limited to only 50 or 100 entries On top of that you ll also need to truncate some names when adding
11. According to the MIDP specification these are the qualifications for a MIDP 1 0 device A minimum screen resolution of 96 54 pixels A minimum of 128kB nonvolatile memory for the MIDP implementation A minimum of 32kB volatile memory for JVM heap space A minimum of 8kB nonvolatile memory for applications to store persistent data Some type of input mechanism Support for network connectivity The OS must provide minimal scheduling exception handling and interrupt processing The OS must support writing of bitmapped graphics to display The OS must be able to accept the input and pass it on to the JVM The MIDP 2 0 specification raises the bar by requiring at least 256kB of non volatile memory and 128kB of memory for the Java heap space However the MIDP 2 0 specification also brings along more functionality for wireless applications including the following Secure networking with HTTPS Push applications with the javax microedition io PushRegistry class Standardized serial port com munications Wireless application deployment with Over the Air provisioning OTA Better gaming applications with the javax microedition ledui game package Developing MlDlets What is a MIDlet A MIDlet is a Java application that runs on a mobile device and uses the Mobile Information Device Profile MIDlets can be created by extending the javax microedition midlet MIDlet class A MIDlet has three states in its life cycle active paused and de
12. NoSuchSessionException java lang Throwable cause Interface ObexEvent public interface ObexEvent extends Event An event indicating that an OBEX related action has occurred in the BlipServer Package com ericsson blipnet api event Methods boolean equals java lang Object obj Returns true if content of object is equal to this java lang String getMimeType Returns the mime type of the OBEX object to which this event is related int getObexResponseCode Returns the OBEX Response Code associated with this event if any java io File getPath Returns the path of the file to which this event is related BluetoothAddress getTerminalID Returns the Bluetooth device address of the terminal to which this event is related Class ObexFile public final class ObexFile extends java lang Object implements ObexPushObject Implements an OBEX push object containing a file Package com ericsson blipnet api obex pushobjects Constructors ObexFile java io File file Constructs an OBEX push object representing the specified file ObexFile java io File file byte b Constructs an OBEX push object containing the bytes of the specified byte and with the specified filename Methods java lang String getAbsoluteFileName byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String
13. RFCOMM is commonly known as the wireless serial port or the cable replacement protocol The name is derived from the fact that your serial ports are called COMM1 COMM2 etc RFCOMM simulates the functionality of a standard serial port For instance a Bluetooth enabled PDA would use the RFCOMM layer to synchronize its data to a Bluetooth enabled PC as if they were physically connected by a cable Telephony Control Protocol Specification TCS TCS Binary TCS BIN Telephony Control Protocol Specification TCS TCS Binary TCS BIN is used to send control signals to devices that want to employ the audio capabilities within Bluetooth For example a Bluetooth cordless phone would use this layer of the protocol to send signals to the base station indicating that the user has requested to hang up the current call or to use call waiting or to place a three way call etc Wireless Access Protocol WAP If you ve used an Internet enabled wireless phone before then you ve used WAP In Bluetooth this is an adopted protocol so the Bluetooth SIG has incorporated the existing WAP protocol into the Bluetooth protocol to fit Bluetooth s needs WAP requires that PPP IP and UDP be present in the stack Object Exchange OBEX OBEX is a communication protocol initially defined by the Infrared Data Association IrDA Unless you ve worked with infrared you ve probably haven t heard of OBEX Just like WAP OBEX was defined by another group but it was ad
14. null OutputStream op null public Client throws IOException InterruptedException localDevice LocalDevice getLocalDevice discoveryAgent localDevice getDiscoveryAgent device new RemoteDevice 10 Starts inquiry for devices in the proximity and waits till the inquiry is completed System out println nSearching for Devices n discoveryAgent startInquiry DiscoveryAgent GIAC this synchronized this this wait Once the Device inqui ry is completed it starts searching for the required service Service search is done with the given uuid After starting each search it waits for the result If the connectionURL is nul ie if No service Records are obtained then it continues search in the next device detected int attrSet 0 3 4 0x100 UUID uuids new UUID 1 uuids 0 new UUID 1111 true for int i 0 i lt count itt int transactionid if transactionid synchronized this this wait if connectionURL break end of forloop discoveryAgent searchServices attrSet uuids device i this 1 null If the URL returned from SPP Server begins with btspp then we call the getConnection method which establishes a connection with the SPPServer and returns it Connection returned is of type StreamConnection A piece of raw data is being sent over RFCOMM if connectionUR
15. on Chip SoC architectures The memory footprints for Embedded Linux and Embedded Windows also known as Windows CE NET were simply too large to even think about SoC Secondly by creating their own OS Smart Network Devices can have a highly efficient network and data communication architecture which is optimized for the underlying platform All interprocess communication is event driven and takes place through an internal message system The HyNetOS is based upon a highly efficient multitasking real time kernel only 16kB in size and is written entirely in Hyperstone assembler On top of the kernel is a complete operating environment that consists of following components Device manager Protocol manager File manager a Java Virtual Machine The device manager is simply a layer that abstracts the underlying hardware and the protocol manager is a layer that implements the TCP IP and Bluetooth protocol stacks The multifaceted file manager can handle different file systems including RAM disk and flash disk as well as external memory cards we ll cover the details of the JVM in the next section Figure 10 6 gives an illustration of the overall structure of the HyNetOS Java Applications Java APIs Java API for TCP UDP Serial for Bluetooth Native C z L Applications Java KVM CLDC De of Asynchronous Event Handler Protocol Manager TCP IP PPP Bluetooth Device Manager Hardware Ab
16. 0 dataSize String fileName new String fileNameAsBytes System out printin File Name is fileName FileOutputStream toFileStrm new FileOutputStream new File fileName try System out printin Starting to Receive file Body receive File body while true if l2capConn ready dataSize l12capConn receive data after the whole file an empty packet is sent from the other end if dataSize 0 System out printin Signal to Stop recieved toFileStrm close toFileStrm null printFile fileName break toFileStrm write data 0 dataSize try Thread currentThread sleep 10 catch Exception genExp finally try l2capConn close catch Exception genExp catch Exception genEx public static void main String args throws Exception JPSBluetoothPrint srv new JPSBluetoothPrint srv connectToClientAndPrint Listing 6 3 has the code that a client would use in order to submit a file to the print server This code would run on any Bluetooth enabled J2ME device Listing 6 3 JPSBluetoothPrintClient java import import import import public java de java util javax bluetooth javax obex class JPSBluetoothPrintClient implements DiscoveryListener ocalDevice local null public JPSB int String servi DiscoveryAgent agent null attrSet nul
17. 512 4 Phone Cellular 512 8 Phone Household cordless 512 12 Phone Smart phone 512 16 Phone modem 768 0 LAN network access point Fully available 768 32 LAN network access point 1 17 utilized 768 64 LAN network access point 17 33 utilized 768 96 LAN network access point 33 50 utilized 768 128 LAN network access point 50 76 utilized 768 160 LAN network access point 67 83 utilized 768 192 LAN network access point 83 99 utilized 768 224 LAN network access point 100 utilized no service available 1024 0 Audio video device Unassigned misc 1024 4 Audio video device Headset must conform to the Headset Profile 1024 8 Audio video device Hands free device 1024 16 Audio video device Microphone 1024 44 Audio video device VCR 1024 72 Audio video device Video game system 1280 64 Computer peripheral Keyboard 1280 128 Computer peripheral Mouse trackball etc 1280 12 Computer peripheral Remote control 1536 16 Imaging device Display device 1536 32 Imaging device Camera 1536 64 Imaging device Scanner 1536 128 Imaging device Printer 7936 Unclassified major device IThis table has a majority of the major and minor device classes listed in the Bluetooth Assigned Numbers document on the Bluetooth Web site http www bluetooth org So that s about all it takes to perform device management with the Java Bluetooth APIs Now let s take a look the concept in Bluetooth that allows you to discover other Bluetooth devices device d
18. 5agRoFvNdQiGDQEPA4GtrIjA8 Y6UFvXskQq4w37vwyUoyvS9ONYxGPOeHEA YkO0b CjA3i6aFIH81IPksb8pNgrt vOmgsXPFSaYbvLveErCQh6wd63cGzKL8023StOIkXi rBafFYa7EutVjc78mTe9vVlWIdw6zyhb35bnaybrLEPW xp2KbelsoiiHngL5MK M4fgqruoPp2k7UOnzwOtflEojEZ8nyOvJCPOZARHhzNAonA6zB 0f2ygNnNtsEald 1O0CiIGKohIMm0a07VTIXx7cmxXUCToSuorlgF43KNs 3wP InPPvxlV3 MhuG4DHE 6 Tm oVcR5 jdfbFRbbUjzLHVPntP QSONE2LAxLsbfMO6zEkz2F2iJLGbOFy8ejeteOXJ jn G1 z4TiOMt yvA1T6 d9qUP7TYsBmrQyLLF 60PCMVOsnE26 mLH9gn4sgPdPhv y8ZHjtSfyon5t vgyY 6tgrY OSB6GypgN8b2v RCi9y5WnsNA010W6Xm iKowTEQAB J7YxBkoPqC2e0fKwZnAgMcImunFX1767ewlOkcBTiWvOsQ2 jOZImD9Fulxpywdfk 5GLoVny3yXRXHLrAbxysNU 0ylOdRNiPE jvnLG2NpxXiCt cWAvuGGw4SID9FIkRiM Dw D p4OgrachGmhZ2rwn9HPIkHjvxbTwtmlgqRx1t 99yBtP 6m fDEWKI8QibLVYr 2RUELEF 3Ak hVd2er82X jeNbgerhbf CS0Ld9w rACL As we stated earlier Bluetooth uses symmetrical encryption so there s only one key for encrypting and decrypt information However the key is never transmitted from the server to the client The encryption key is derived fri several factors that are known to both the client and server including the PIN Now let s take a look at how to your data transmissions using the JSR 82 Server Encryption Bluetooth servers can specify that they want their transmissions encrypted by setting the encrypt parameter t in the connection URL as follows String url btspp 02AB45AC
19. Delays in sending and receiving information are dependent on factors such as the physical medium traffic on the network and information routing algorithms Bandwidth is not constant Like latency there is often no guarantee of transmission capacity Networks are insecure This is especially true of heterogeneous networks where the devices exchanging information cannot control the path that the information takes Network topologies are variable This is most obvious in mobile networks when devices move between network access points Now and in the near future multimode devices will move between network types e g from a cellular network to a wireless local area network to a wired desktop network Administration of networks is not uniform Multiple networks provide their own sets of rules protocols access authorization and security protocols all controlled by different organizations and individuals Accessing and securing resources across these networks will be complicated because of inconsistent administration practices Access and transportation costs are variable a Many different devices with different configurations capabilities and operating systems will participate in the network Jini federations are agnostic to the type of connection between the devices participating in the network It doesn t matter if the participants are connected physically or wirelessly the only requirement is that the connections are TCP I
20. Disabled Page Scan Enabled Constructors ScanMode int value Constructs a ScanMode object representing a valid Scan Mode Methods boolean equals java lang Object obj int getScanMode Returns the scan mode represented by this object int hashCode java lang String toString Class Session public final class Session extends java lang Object implements java io Serializable Thesession class encapsulates the session types supported by the BlipServer Package com ericsson blipnet api Bluetooth Fields static java lang String FRIENDLY_NAMES T Friendly names of the defined session types static long LAP_CLIENT LAN Access Profile LAP Client session type static long LAP_SERVER LAN Access Profile LAP Server session type static long OPP_CLIENT Object Push Profile OPP Client session type static long OPP_SERVER Object Push Profile OPP Server session type Constructors Session long sessionType Constructs a Session object representing the specified session type Methods boolean equals java lang Object obj long getSessionType Returns the type of this session object int hashCode java lang String toString Class ShortUuid public final class ShortUuid extends java lang Object implements java io Serializable TheShortUuid class models a Bluetooth universal unique identifier This is a 16 bit unsigned integer o
21. Figure 2 3 The Palm SD Bluetooth card for Palm OS 4 devices Palm OS is a registered trademark of Palm Inc Figure 2 4 You can only connect to one Bluetooth device at a time if you have hardware that only supports point to point communication Figure 2 5 You can connect to up to seven Bluetooth devices at a time if you have multipoint capable hardware Figure 2 6 A The computer may be attached to its peripherals but it can t control them without a driver B The computer may be attached to a Bluetooth device but it can t control it without a stack Figure 2 7 The Bluetooth protocol stack Figure 2 8 As you can see in Windows 2000 the operating system thinks that COMM10 and COMM11 are actual serial ports Figure 2 9 Bluetooth profile interdependencies Figure 2 10 In apiconet the slaves can only communicate to the master Figure 2 11 A scatternet is formed when a slave in one piconet is the master in another piconet Chapter 4 Understanding the Java Bluetooth API Figure 4 1 Service records in the SDDB Figure 4 2 An individual attribute of a service record Figure 4 3 An illustration of a service record attribute Figure 4 4 DataElements Figure 4 5 The service discovery process for a PDA that wants to use the services of a Bluetooth keyboard Chapter 5 Bluetooth with J2ME MIDP Fiqure 5 1 J2ME Profiles and configurations Fiqure 5 2 A logical representation of an RMS record store Figure 5 3 The application s
22. Figure 9 7 With encryption enabled the Protocol Analyzer is still able to capture the data transmission however the data is corrupted More on Mobiwave BPA D10 Given sufficient information the Mobiwave Protocol Analyzer could decrypt those encrypted packets over the air The Mobiwave Protocol Analyzer is equipped with a feature called SmartDecrypt SmartDecrypt wa designed to tackle the noisy RF environment so that all the seven client slave sessions could be decrypted in real time Here s what you need to do in order to enable SmartDecrypt on the Mobiwave BPA D10 The first thing that you need to do is to add the slave devices to the list of known slave devices From the BPA D10 main menu select Decryption and then select Decryption Setup This brings up the slave list dialog box shown here Click Add to bring up the Add New Slave dialog box as shown here BO ADORA H0803 14 1DAE x If the PIN is not available or defined enter HEX 00 this is the default PIN If the current link key is known you can enter it else leave this field blank Click OK when you are done The current link key if not specified will be automatically generated during the capture of a good pairing or bonding session between the two Bluetooth devices Now let s run the security sample application again with the encrypt parameter set to true Remember to set the same PIN code you used to configure your slave device in the BPA D10 The following figure i
23. do is to set the mirrors seats and radio stations just once and store your preferences on a Bluetooth enabled device that you carry with you all the time like a wireless phone PDA or a watch It wouldn t matter if someone else used your car because all your preferences are stored on the device you keep with you After someone uses your car all you need to do is upload your preferences from your Bluetooth enabled device like your watch see Figure 1 3 and be on your merry way Figure 1 3 Although the Fossil Wrist PDA doesn t contain any Bluetooth hardware it does come preloaded with a Bluetooth enabled OS the Palm OS 4 1 Palm OS is a registered trademark of Palm Inc The New Arcade A Restaurant Lobby Finally let s say that sometime in the near future you and several other people are waiting for aseat ata restaurant While you are waiting for your table the hostess gives you a little gaming device to help you kill time This Bluetooth enabled device not only lets you play games against the computer but you can also play games with other people in the lobby When your table is ready your game unit vibrates automatically so the hostess doesn t even need to call you When you turn your device in to the hostess your score is automatically uploaded to the high scores list If your score is good enough you may even win a free meal Summary Bluetooth is a great technology for wireless connections between power conservative
24. large solid state disk Since HyNetOS comes built in with an FTP server this flash disk can easily be administra using any FTP client program In order to specify device drivers or interfaces that you would like to see started with HyNetOS after a system re need to edit a configuration file named JSTARTUP INT This file can also be used to designate the class files t want be executed at boot time A typical JSTARTUP INI would look like this devices COM1 COM2 ETHSMSC111 LCD12864 KEYPAD BLUETOOTH protocols TCP IP BLUETOOTH applications myapp class Operating System Tools Several tools are provided to the user in order to perform common sysadmin tasks on the Micro BlueTarget Yc do things like load a new OS reboot the system format the flash disk and trace the application code All these are Java desk top applications J2SE and can be executed on any Java enabled platform HYFLASH HYFLASH is an administration tool for the Micro BlueTarget s flash memory the flash disk It can check and u the ROM section format the flash disk and upload content from any directory on your PC to the target system HYLOAD HYLOAD is the dynamic OS loader If the HyNetOS is already stored on the flash disk the bootloader will automatically boot the system after a system reset At runtime however an OS restart can always be triggered HYLOAD while dynamically uploading a newer version of the OS HYMON HYMON
25. the Rococo Palm DK no code is needed at all to initialize your stack In other cases you ll need to write a bit ol code to get your stack initialized because you need to specify baud rates for your RS 232 interface For instance Listing 4 1 shows the snippet of code that you would need in order to initialize your stack if you we using the Atinav SDK with a RS 232 based Bluetooth device Listing 4 1 Stack Initialization Code for the Atinav SDK import com atinav bcc BCC setPortName COM1 BCC setBaudRate 57600 BCC setConnectable true BCC setDiscoverable DiscoveryAgent GIAC Esmertec takes a different approach for stack initialization Their JSR 82 implementation and stack tends to be used mostly by wireless device OEMs Listings 4 2 and 4 3 show the Java classes that would be part of a startu sequence to initialize the stack for the entire device After the device has started which consequently means th the stack is also initialized other Java applications that reside on the device no longer need to include code to initialize the stack Listing 4 2 BluetoothSetup1 java import com jbed bluetooth import java io IOException public class BluetoothSetupl private static int device private static BCC myBCC static device DeviceProperties DEVICE_1 try myBCC BCC getInstance myBCC startUp device myBCC initDriver System out printin Bluetooth Started catc
26. you will see that the responses are modeled after their HT TP counterparts E OBEX DATABASE FULL m OBEX DATABASE LOCKED E OBEX HTTP ACCEPTED m OBEX HTTP BAD GATEWAY E OBEX HTTP BAD METHOD m OBEX HTTP BAD REQUEST E OBEX HITP CONFLICT mE OBEX HTTP CREATED E OBEX HTTP ENTITY TOO LARGE E OBEX HTTP FORBIDDEN E OBEX HTTP GATEWAY TIMEOUT m OBEX HTTP GON E E OBEX HTTP INTERNAL ERROR E OBEX HTTP LENGTH REQUIRED E OBEX HTTP MOVED PERM m OBEX HTTP MOVED TEMP E OBEX HITP MULT CHOICE m OBEX HTTP NO CONTENT E OBEX HTTP NOT ACCEPTABLE m OBEX HITP NOT AUTHORITATIVE E OBEX HTTP NOT FOUND m OBEX HTTP NOT IMPLEMENTED E OBEX HTTP NOT MODIFIED m OBEX HITP OK E OBEX HTTP PARTIAL m OBEX HTTP PAYMENT REQUIRED Tr E OBEX_HTTP_PRECON_FAILED m OBEX_HTTP_PROXY_AUTH E OBEX HTTP REO TOO LARGE mE OBEX HTTP RESET E OBEX HTTP SEE OTHER m OBEX HTTP TIMEOUT E OBEX HTTP UNAUTHORIZED m OBEX HTTP UNAVAILABLE E OBEX HTTP UNSUPPORTED TYPE m OBEX HITP USE PROXY E OBEX HTTP VERSION Note So where are the response codes that we discussed earlier in this chapter l
27. Bluetooth kit vendor is if their product is JSR 82 compliant Currently JSR 82 can only be implemented on the J2ME platform JSR 82 cannot be implemented on the J2SE platform because the J2SE does not support the Generic Connection Framework Hopefully the Generic Connection Framework will be implemented by JDK 1 5 Note The official JSR to implement the GCF in the JDK is JSR 197 Does this mean that it is impossible to do Java and Bluetooth development on the J2SE platform No it simply means that whatever Java Bluetooth kit that you obtain for J2SE will not be compliant with JSR 82 until the Generic Connection Framework is implemented in J2SE The major ramification of this problem is that your J2ME and J2SE code may be drastically different from each other even if you are doing the same thing Java Bluetooth Vendor SDKs So who s offering Java Bluetooth SDKs and which are JSR 82 compliant Fortunately there is a plethora of Java Bluetooth SDKs to fit the needs that your application requires Vendor support is available for Java Bluetooth development on a wide range of operating systems and JVM platforms Table 3 3 displays various attributes of many Java Bluetooth SDKs Table 3 3 Java Bluetooth SDK Vendors l COMPANY JSR 82 JSR 82 SUPPORTED SUPPORTED NAME JAVAX BLUETOOTH JAVAX OBEX JAVA OPERATING SUPPORT SUPPORT PLATFORMS SYSTEMS Atinav Yes Yes J2ME J2SE Win 32 Linux Pocket
28. BluetoothSetup1 java listing 47 48 BluetoothStateException class 259 BNEP Bluetooth Network Encapsulation Protocol 22 252 Bootloader section ROM 188 BTAUTOLAN CFG file 192 Btgoep protocol 128 Building tracking employees in 229 Index C C Cbased Bluetooth SDK 39 Cable replacement protocol RFCOMM 21 25 67 70 72 Cable replacement technology Bluetooth as 2 5 CACHED device explained 56 57 Car Bluetooth in 7 8 CAST algorithm 160 161 CDC connected device configuration 75 Cell phones configuring in Impronto Simulator 143 and laptop connection sharing 5 limitations of 3 and PDA data transfer 3 4 Centralized communication 226 Challenge response mechanism 156 Chat example 145 152 ChatClient java listing 146 150 ChatServer Bluetooth device 151 ChatServer conversation 152 ChatServer interacting with ChatClient 151 ChatServer java listing 145 146 Cipher encryption algorithm 159 Class 1 Bluetooth devices 17 225 Class 2 or Class 3 Bluetooth devices 17 225 CLDC connected limited device configuration 75 76 186 CLDC packages for small device Java applications 76 CLDC Technology Compatibility Kit TCK 186 Client authentication 157 Client authentication request 157 Client connections with Serial Port Profile 69 70 Client encryption 162 163 Client server architecture Bluetooth 1 ClientApp java listing 165 170 ClientSession interface javax obex 122 265
29. ESSION_NOT_CREATED Session not created static int CAUSE_SYSTEM_ENDED_CONNECTION System ended connection T H static int CAUSE_UNEXPECTED_TERMINAL_BEHAVIOR Unexpected terminal behavior static int CAUSE_USER_ENDED_CONNECTION User ended connection Interface BlipNodeEvent public interface BlipNodeEvent extends Event An event which indicates that a BlipNode related action occurred in the server Package com ericsson blipnet api event Methods boolean equals java lang Object obj Returns true if content of object is equal to this java lang String getApplicationName Returns the name of the user application which has un locked the Bl ipNodeHand1e for the BlipNode specified in this event java lang String getBlipNodeFriendlyName Returns the friendly name of the BlipNode which initiated this event java lang String getBlipNodelIP Returns the IP address of the BlipNode which initiated this event java lang String getBlipNodeSoftwareVersion Returns the software version of the BlipNode which initiated this event int getCause Returns the cause of the event Interface BlipNodeHandle public interface BlipNodeHandle ABlipNodeHandle provides an application access to a physical BlipNode A BlipNodeHandle is obtained through a BlipServerConnection When an application has acquired a BlipNodeHandie that
30. Exchange Profile the SDK vendor or the application developer is free to implement the higher profiles of the Bluetooth specification What You Need to Get Started We know that this question has been on your mind for a while Well here s a list of what you ll need Bluetooth devices at least two Bluetooth host at least one m Bluetooth stack Java Bluetooth API Now let s cover all these components in detail and describe how they all work together Bluetooth Devices Bluetooth devices were covered in Chapter 2 but just in case you forgot take another look at Figures 2 1 2 2 and 2 3 Remember Bluetooth devices are simply radios so getting a single device is just like getting a single walkie talkie it s pretty useless If your Bluetooth device is point to point capable then that means it can only talk to a single Bluetooth device at a time If it is multipoint capable then it can talk to up to seven devices at a time The Bluetooth device is also known as the controller Bluetooth Host The Bluetooth host is the computer that is physically connected to the Bluetooth device For the most part this is your desktop PC laptop PDA or smart phone Usually the connection is USB RS 232 or UART Now you are definitely going to need two Bluetooth devices but you can get away with having only one Bluetooth host How does this work Well if you have a PC that has two serial ports or two USB ports or both then you can connect
31. Expert Group also had three individual experts Peter Dawson Steven Knudsen and Brad Threatt What Is the Rl and TCK According to the Java Community process the specification lead company is responsible for creating a Reference Implementation RI and also a Technology Compatibility Kit TCK The Reference Implementation is basically a proof of concept to prove that the specification can be implemented Other companies are free to implement the JSR 82 and in order to certify that their vendor kit is compliant to the JSR 82 standard that vendor s product must pass the TCK The JSR 82 specification actually has two Reference Implementations and Technology Compatibility Kits Why did they do this Recall in Chapter 2 that the Bluetooth SIG has adopted some preexisting protocols in the Bluetooth specification namely OBEX The OBEX protocol was used with infrared technology for object transmissions long before Bluetooth was even invented The designers of the Java Bluetooth specification decided not to tie OBEX to Bluetooth when creating the Java Bluetooth standard Therefore the JSR 82 actually consists of two independent packages m javax bluetooth the 13 classes and interfaces that are needed to perform wireless communication with the Bluetooth protocol a javax obex the 8 classes that are needed to send objects between devices independent of the transport mechanism between them So to answer your next question yes you can use OBE
32. Java Bluetooth APIs Demo applications Installation Installation is pretty simple In order to run the installer just execute devkit exe and follow the on screen instructions The installation of the Impronto Developer Kit will also install WebSphere Micro Environment To complete your installation install the necessary prc files on your PDA The Impronto Developer Kit files are m idev midp j9 prc m idev racs prc m idev utils prc m idev wrap prc The J9 VM prcs are named m edlel5 pre m j9 vm bundle prc m jOpref prc m midpl5 pre After you have completed your installation verify that everything is correct by running the sample application MIDP Chat A screenshot of this application is shown in Figure C 2 Figure C 2 The MIDP Chat application Appendix D BlipNet 1 1 API This appendix presented here with permission from Ericsson contains descriptions of all the fields and method signatures of the classes interfaces and exceptions that comprise the BlipNet 1 1 API Note For more information about BlipNet see http www ericsson com blipnet Class BlipNeticons public class BlipNetIcons extends java lang Object Package com ericsson blipnet api util Fields static int BLIPMANAGER_ICON static int BLIPNODE ALARM ICON static int BLIPNODE ICON static int BLIPNODE LOCKED ICON static in
33. PC BlueGiga No No WabaJVM uClinux Ericsson No No J2SE Win 32 Linux Esmertec Yes No J2ME Win 32 Palm OS Pocket PC many others Harald No No J2SE Win 32 Linux others Possio Yes Yes J2ME Win 32 Linux Rococo Yes Yes J2ME J2SE Win 32 Linux Palm OS Pocket PC Smart Yes No J2ME HyNetOS Network Devices SuperWaba No No WabaJVM Palm OS Zucotto No No J2ME J2SE Win 32 IThe information in this table is subject to change so check the companion Web site http www javabluetooth com for up to date information Palm OS is a registered trademark of Palm Inc Summary This chapter has only skimmed the surface of how to integrate Java Bluetooth You learned about the advantages of using Java versus C for application development You also learned about JSR 82 as well as what it takes to get things up and running In the next chapter we ll focus more on integrating Java and Bluetooth as well as introduce some example code Chapter 4 Understanding the Java Bluetooth API This chapter will be your formal introduction to the Java Bluetooth API We ll cover a vast majority of the classe inthe javax bluetooth package and examine how to use them in your applications Rather than looking at every class and interface individually we ll take a different approach by first looking at the basic components of typical Bluetooth application Java or otherwise After we have identified these components we ll explain how t use the Java Bluetooth AP
34. RECORDS public void serviceSearchCompleted int transID int respCode System out printin serviceSearchCompleted transID respCode Removes the transaction ID from the transaction table removeFromTransactionTable transID serviceSearchCount synchronized this this notifyAll Called when service s are found during a service search This method provides the array of services that have been found public void servicesDiscovered int transID ServiceRecord servRecord If this is the first record found then store this record and cancel the remaining searches if record null false i System out printin Found a service transID System out printin Length of array servRecord length if servRecord 0 null System out printin The service record is null record servRecord 0 if record null System out printin The second try was null Cancel all the service searches that are presently being performed for int i 0 i lt transactionID length i if transactionID i 1 System out printin agent cancelServiceSearch transactionID i Called when a device discovery transaction is completed The lt code gt discType lt code gt will be INQUIRY_COMPLE INQUIRY_ERROR if the device discovery transaction failed to compl
35. Service record attributes 59 60 Service records in the SDDB 59 Service registration 65 67 defined 65 process listing 66 67 inthe SDDB 127 ServiceClassIDList 130 ServiceDatabase State 131 Serviceltem leasing 247 249 Serviceltem object Jini 245 247 249 250 252 ServiceName object 69 131 ServiceRecord class 58 59 64 26 ServiceRecordHandle 130 ServiceRecordState 130 ServiceRegistrar object Jini 247 248 250 251 ServiceRegistrationException class 263 Services registering and storing in the SDDB 66 Services Discovered method 64 ServiceT emplate object Jini 250 Session management 226 Session Protocol OBEX 11 7 119 121 SessionNotifier interface javax obex 127 268 Sessions defined 68 SetDiscoverable method 52 SetEnwVars script 140 1 41 SET PATH operation OBEX 121 135 SetPath method 135 Shared link key 156 Shopping malls 226 Signal strength indicator 33 SimpleDoc object 100 101 Simulator Bluetooth 137 153 vs emulator 138 pros and cons of using 138 139 Simulator bin 140 Simulator exe 140 Slave list dialog box 176 Slaves and master concept 1 30 31 Small office Bluetooth in 6 Smart Network Devices 183 185 SmartDecrypt Mobiwave Protocol Analyzer 176 178 SND operating system HyNetOS 185 SoC System on Chip architecture 183 185 Sound applications Bluetooth for 6 7 SPP SeeSerial Port Profile SPP2COMM java listing 208 223 Stack Bl
36. StreamConnection Connector open connectionuURL class WriteThread extends Thread OutputStream op null public WriteThread OutputStream oup op oup public void run int data 0 int i 0 do try data System in read op write data catch IOException e while true public class ChatClient public static void main String args throws IOException InterruptedExceptio System setProperty improntolocaldevice friendlyname ChatClient Client chatClient new Client In order to test the application you need to set the system properties for each class Figure 8 5 shows the Impr Simulator after we ranthe ChatServer application Serece Clauses beer meten recovery Made Geren sl Os oer sro Secu Py Mote Mover erf ve security Ser Com Aapty args Meia Peers Figure 8 5 The ChatServer Bluetooth device in the Impronto Simulator device list Now that the server is running let s open a new command window and run the chat client Figure 8 6 shows the Impronto Simulator with Chat Client making a connection to ChatServer F Biveteeth Simulation Console localhost file Doden Configure Hets Wed ChatServer ChatChent Ohuctes Actress 000037520003 Frondy Mame ChetChent Connectable Device Chass Miscellawous No minor device Prana Rendering Figure 8 6 The ChatServer interacting with the ChatClient in the Impronto Simulator envir
37. WapServiceLoading class are immutable once created they cannot change Package com ericsson blipnet api obex pushobjects Fields static byte CACH Gl Indicates that the WAP service content is loaded in the same way as for EXECUT E LOW but instead of executing the service in the same way as for EXECUT E LOW itis placed in the cache of the client static byte EXECUTE_HIGH Indicates that the WAP service content is loaded and executed in the same way as for EXECUT E LOW but may result in an user intrusive behavior static byte EXECUTE_LOW Indicates that the WAP service content is fetched from either an origin server or from the client s cache if available static java lang String TOKENIZED_MEDIA_TYPE Defines the tokenized form of the WAP Service Loading Media Type Constructors WapServiceLoading java lang String uri Constructs a WapServiceLoading WapServiceLoading java lang String uri byte action Constructs a WapServiceLoading Methods boolean equals java lang Object obj Compares this WapServiceLoading with an Object and returns true if they are equal byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String getObexType Returns the mime type of this ObexPushObject int hashCode Returns a hashCode for this WapServiceLoading java la
38. a Device discovery a Service discovery a Service registration Communication CROSS SeeChapter 4 for more details on the basics of a Bluetooth application REFERENCE Now perhaps you ve heard of Jini as well If you haven t used it before then you should be at least aware that it s a networking technology Jini also happens to be a service oriented technology like Bluetooth ie after you join the network you are able to consume or provide services So if you want to know how to use Bluetooth and Jini together then this is the chapter for you Before we go any further let s first clearly define the following a What is Jini How does Jini work After we answer those two questions we can look at what it ll take to combine Jini and Bluetooth together We ll also look at a device that already integrates Bluetooth and Jini together the PsiNaptic PsiNode What Is Jini Network Technology Jini network technology was created by Sun Microsystems to enable networked devices to communicate and share services with little or no human intervention In part this was in response to their correct perception that the rapidly increasing complexity of the network environment would cause current practices in network management to fail completely Jini set out to solve the following problems with distributed computing Networks are unreliable Connections to other computers may disappear unexpectedly The latency of a network is variable
39. application has exclusive access to the physical BlipNode until the handle is released by calling release If the BlipNode disconnects from the server the handle will be released by the server causing a BlipNodeHandleReleasedException to be thrown when an application tries to use the handle Package com ericsson blipnet api blipnode Methods void addToBlipNodeDenyList BluetoothAddress terminalID Adds the specified device ID to the local deny list on this BlipNode void addToInquiryFilter BluetoothAddress terminalID int timeout Adds the specified terminal to the inquiry filter in this BlipNode void changeInquiryLength int inquiryLength Dynamically configures the length of time in units of 1 28 s in which the BlipNode performs inquiry before restarting inquiry or switching to Scan void changeLinkEstablishmentMode boolean automaticLinkEstablishmentOn boolean nameLookupOn Dynamically switch the BlipNode in and out of automatic link establishment mode void changeScanLength int scanLength Dynamically configures the length of time in units of 1 28 s in which terminals are able to detect the Blip Node during inquiry or paging void changeScanMode ScanMode scanMode Dynamically changes the Scan mode on the BlipNode void clearBlipNodeDenyList Clears the local deny list on this BlipNode void disconnectLink BluetoothAddress terminalID int inquiryFilterTime
40. bo8 YEE JBlpygwWCtw8hP0 jxFG3L hWe950kgu8kNTX SX6bthPBWnvZ7vTgstYyAQ yXLwfLJRYuuT 9i80uqO0Dw3Kc0u3xTwIlE4KIiIvlHwadYv5z2G 70hRWR3awW4gSG9w a2lucyA8YmhvcGtpbnNAZ2x0Zy5 jb20 i0BYBBARAgAYBOI 9WUceCAsCAwk IBwEK AhkBBRsSDAAAAAAOJEJION wlq4wQWDAAnAmrZRbJXWARLbowLBwfTrJmMfhwAJ9V 14770H3TB W2SLbJOSLY 9gG1CW7kCDOQQ 9WUceEAGgA Ik IXtwh CBdyorrWqULzBej5 UxE5T7bxbr1LOCDaAadWoxTpj0BV8 9AHxstDqZSt 90xkhkn4DIO9ZekX1KHTUPJ1 WV cdlJPPT2N286Z4VeSWc3 9uK50T8X8dryDxUcwYc58yWb Ffm7 ZFexwGq0lue jaClcojrUGvC RgBYK X0iP1YTknbzSCOneSRBzZrM2w4DUUdD3yIsxx8Wy209vPJU I8BD8KVbGI20u1WMUuF040zT9FBAXQ6MdGGzeMyEstSr POGxKUAYEY18hKcKctaG xAMZyAcpesqVvDNmWn 6vOC1LCbAkKbTCD1ImpF1iBn5x8vYlLIhkmuquiXsNV6TILOWAC Agf M1E08J4AnzN20aLhjb081jrdUn5BIVPkHxm6smP5riIHJ4kpmkoLJstXV P7HD rWaQXBqBzx0wEchZL S7qazRQA6dQ08e2fSeMOABOgo7pD 4DEn1rKitTh5501qFK6 yH t pEC C9zkpeLNEODK v1lwK3j7X1 d8gEUYxoDALbQ5rZ5e3eTEut 3WFMAIp6AQ Z14BKmP4RYw8ij21LEHPJ F 6aAZAmzp7U 2HEVOH 7ZrZogz0dmOrAIMpRHgPVsI uOryEYXSdsG613s5xgqY4JRON96hg38G6Z45V4 22kt 5uncxXWbupmOXt yyxBW5roxb W AS2KMkb6Y5s0sSsfQ63inD8IkATAQYEQTADAUCPV1HHgUbDAAAAAAKCRCSND 8 NauMECO3AKD1U0nZcLkmDx0CGCbJwmp2m0P 2 jwCg0 3KNtDRx6FyyZpZc5QRAWbgP P4M trVX Listing 9 3 Bank Account Information Encrypted with the CAST Algorithm qANQR1DBwWU4DMCkFM4tTfBSQCAC4WJhOUK50sv3gZJ3ivf5BUb jm9R6n2vKUijp KUzu3B1PSS3ignZ9t1Bvp HSXuX31Bq8KsoMYYSwj3QLSkKgYJz1PkAyvyR9bXed
41. both of your Bluetooth devices to your PC s ports In order for this to work you need to start two instances of your JVM each JVM will have its own Bluetooth device The Bluetooth host must meet the minimum requirements for the CLDC so you need at least 512k total memory for the JVM Bluetooth Stack A Bluetooth stack is required in order for a Bluetooth host the PC to properly communicate to the Bluetooth device the controller If you go back to Figure 2 6 which shows a diagram of the Bluetooth stack the bottom layer of the stack is the Host Controller Interface See it does make sense The Host Controller Interface is literally the software required to interface the Bluetooth host and the Bluetooth device the controller Since this book is all about Java and Bluetooth you might think that the Bluetooth stack needs to be written completely in the Java language Well not exactly Some Bluetooth vendors have implemented a completely all Java stack while others have implemented a Java interface i e JNI or other means to a native stack Either way you need to access the stack through Java code whether or not the stack is in Java Java Bluetooth API Finally you re going to need a set of libraries to interface with your stack For the most part acompany will sell you a Java Bluetooth API and Bluetooth stack together in a kit Just be sure to ask them what Bluetooth devices their kit supports Another question to ask your Java
42. but can get really expensive if you have more printers On the other hand if you re a business user you probably have a whole network of printers available at your disposal Buying a printer adapter for each and every printer in a corporate environment really doesn t make a lot of sense This chapter gives you a handy utility that will turn your desktop computer into a Bluetooth print server using the Java Print Service JPS API If your desktop computer already has the drivers and mappings that are necessary to print to your printers why not utilize it Your mobile device can submit print jobs to your desktop computer and your desktop will automatically print the file to one of your printers using JPS see Figure 6 2 Figure 6 2 Using the handy utility provided in this chapter you can turn your desktop into a Bluetooth print server JPS Overview The relationship between a printer and its client is pretty simple The client needs to answer two questions a Whatto print How to print it In turn the printer also needs to answer two questions a What s the status of the printer itself a What s the status of the print job The exchange of information between the printer and its client takes place by means of three entities within the JPS architecture documents attributes and events Note Consequently the JPS API consists of the following packages javax print javax print attribute javax print attribute standard and javax p
43. cables On the other hand Bluetooth is intended to connect smaller devices like PDAs and mobile phones within a range of 30 feet at a rate of 1 Mb s Slower data rates and shorter ranges allow Bluetooth to be a low power wireless technology Compared to 802 11b devices some Bluetooth devices can easily consume 500 times less power which can make a huge difference in the battery life of many mobile devices Bluetooth is also intended to be used as a cable replacement technology If you have multiple peripherals connected to your computer using RS 232 or USB then Bluetooth is the ideal solution if you want to use those devices wirelessly It s almost impossible to connect peripherals to your computer using 802 11b technology well except for printers Bluetooth even has a built in capability for wireless audio communication Can either technology replace the other Hardly Bluetooth will never replace 802 1 1b because it s bad at handling the following Large file transfers between devices m Long range communication only Class 1 Bluetooth devices have a range of 300 feet CROSS See Bluetooth Device Power Classes in Chapter 2 for details about power REFERENCE classes On the other hand 802 11b will never replace Bluetooth because 802 11b can t be used to communicate to peripherals 802 11b requires too much power for communication 802 11b is overkill for small data transfers 802 11b wasn t designed for voice communication
44. classes and interfaces that are a part of the JPS API Now in order to create a Java Print Service application you need to do the following 1 Identify the format of the data to be printed ie GIF JPEG PDF HTML etc 2 Search for a print service that supports your data format 3 Create a print job and submit it 4 Listen for status updates optional Printers and Print Services If you re new to the JPS you may say to yourself know what a printer is but what s a print service In JPS a javax print PrintService object is a logical representation of an actual printer So instead of printing to a printer you ll print to a print service Identifying the Format The first thing to do is identify the data format The class that allows you to do this is javax print DocFlavor For instance if you wanted to tell the print service that you want to print out GIF files then the code would look something like this DocFlavor docflavor DocFlavor INPUT_STREAM GIF The JPS also has the functionality built in to print other popular binary formats like PDF PostScript PNG and JPEG Creating a Document Now that you ve specified a document format the next step is to create a document All documents in JPS must implement the javax print Doc interface You can implement this interface yourself or you can use the javax print SimpleDocobject to encapsulate your data into a document Following is a snippet of code that demonstrate
45. content like HTML pages images files and best of all Java applets A Web server also uses an HTTP protocol stack to send out Web content to Web browsers over the network So like the HTTP protocol stack a Bluetooth protocol stack will allow Bluetooth clients and servers to send and receive data over a wireless network So how do the Bluetooth device and the Bluetooth stack work together What is their relationship Well a Bluetooth device without a stack can be compared to a computer without an operating system More specifically it s like a computer peripheral without a driver Figure 2 6 illustrates this concept Figure 2 6 A The computer may be attached to its peripherals but it can t control them without a driver B The computer may be attached to a Bluetooth device but it can t control it without a stack So in order to communicate with the Bluetooth protocol and to control a Bluetooth radio your computer uses a Bluetooth stack Now let s break down the Bluetooth stack into its individual components and see how they work Each component of the stack is called a layer Layers of the Protocol Stack For application developers the Bluetooth protocol can be broken up into two main items layers and profiles All the layers of the Bluetooth protocol form the protocol stack Figure 2 7 shows how the following layers of the Bluetooth protocol stack up Host Controller Interface HCI Logical Link Control and Adaptation Prot
46. course this works well if the app is a JSR 82 application Clients compose their e mail using the custom application and when they are ready to send the e mail they simply come within range of an e mail station and push the e mail OBEX object to the BlipNode On the BlipServer your enterprise Bluetooth application will be listening for an Object Push event and will connect to an e mail server to send the e mail on behalf of the hotel guest Note This might be a perfect time for you to try creating custom headers for your OBEX e mail object There s nothing stopping you from defining a custom header for the to from and subject fields for the e mail As you can see the wireless e mail station scenario clearly demonstrates the difference between the programming paradigms of the JSR 82 and the BlipNet Using the JSR 82 you can create the client app that generates the e mail OBEX object and pushes it to the server One of the major drawbacks however is that you need to implement the Object Push Profile in your application code which may be an inconvenience for inexperienced developers On the other hand the Object Push Profile is already defined within the BlipNet API so all you need to do is write the event handling code when your object arrives from your Bluetooth enabled clients BlipNode Installation Installation of a BlipNode is pretty simple All you need to do is supply the Ethernet connection and power The device will then
47. else System out printin Record is null return false Finds the first cable replacement peer that is available to connect to public ServiceRecord findCableReplacementService If there are any devices that have been found by a recent inquiry we don t need to spend the time to complete an inquiry RemoteDevice devList agent retrieveDevices DiscoveryAgent CACH if devList null El is if searchServices devList return record Did not find any cable replacement peer from the list of cached devic Will try to find a cable replacement peer in the list of pre known devices devList agent retrieveDevices DiscoveryAgent PREKNOWN if devList null if searchServices devList return record Did not find a cable replacement peer in the list of pre known or cached devices So start an inquiry to find all devices that could be a cable replacement peer and do a search on those devices try agent startInquiry DiscoveryAgent GIAC this Wait until all the devices are found before trying to start the service search synchronized this try this wait catch Exception e catch BluetoothStateException e System out printin Unable to find devices to search if deviceList size gt 0 devList new RemoteDevice deviceList size de
48. ericsson blipnet api blipnode Constructors BlipNodeHandleReleasedException BlipNodeHandleR asedException java lang String s BlipNodeHandleReleasedException java lang String s java lang Throwable e Class BlipNodeNotConnectedException public final class BlipNodeNotConnectedException extends BlipServerException Thrown by a BlipServerConnection when an application tries to get a Bl ipNodeHandle for a BlipNode which is not connected to the server Package com ericsson blipnet api blipnode Constructors BlipNodeNotConnectedException BlipNodeNotConnectedException java lang String s BlipNodeNotConnectedException java lang String s java lang Throwable e Class BlipServer public final class BlipServer extends java lang Object Factory class for getting BlipServerConnections Package com ericsson blipnet api blipserver Constructors BlipServer Methods static getConnection java lang String username BlipServerConnection java lang String password java lang String serverHost Returns aBlipServerConnection to the specified server using default values for port number and service name static getConnection java lang String username BlipServerConnection java lang String password java lang String serverHost int serverPort java lang String serverServiceName Returns aBlipServerConnection to the specified server Class BlipServ
49. event indicating that a terminal has been detected by a BlipNode in Inquiry Only Mode Package com ericsson blipnet api event Methods PageData getPageData Returns the Paging data needed for direct paging of this terminal Interface Link public interface Link extends java io Serializable TheLink interface provides methods to retrieve snapshot information about a specific BlipNode T erminal link Package com ericsson blipnet api Bluetooth Methods boolean equals java lang Object obj Compares this LinkImp1 with an Object and returns true if they are equal BluetoothAddress getBlipNode Returns the BluetoothAddress of the BlipNode using this session int getCurrentSessions Returns an array of active sessions on this link BluetoothAddress getTerminal Returns the BluetoothAddress of the terminal using this session boolean isSessionActive long sessionType Tells whether the indicated session type is active java lang String toString Implements the toString method Class NoSuchSessionException public class NoSuchSessionException extends java lang RuntimeException Thrown by a BlipNodeHandle to indicate that an attempt was made to close a non existing session Package com ericsson blipnet api blipnode Constructors NoSuchSessionException NoSuchSessionException java lang String message NoSuchSessionException java lang String message java lang Throwable cause
50. for Tracking java is shown in Listing 11 1 Listing 11 1 Tracking java package com ericsson blipnet samples import com ericsson blipnet api e import com ericsson blipnet api blipserver import com ericsson blipnet api bluetooth BluetoothAddress import com ericsson blipnet api blipserver BlipNode vent import java util Hashtable public class Tracking private BlipServerConnection blipServerConnection private Hashtable terminalLastSeenOnThisBlipNode new Hashtable public Tracking String discoverBlipNodeGroup BluetoothAddress terminalsToTrack Get a connection to the server initBlipServerConnection BlipServerEventFilter blipServerEventFilter getEventFilter discoverBlipNodeGroup terminalsToTrack try Register th vent Listener with the generated filter blipServerConnection addEventListener new TrackingEventListener blipServerEventFilter catch BlipServerConnectionException e System out printin Error attaching listener e printStackTrace System exit 1 private void initBlipServerConnection Gry blipServerConnection BlipServer getConnection Tracking Tracy localhost catch BlipServerConnectionException e System out printin Error connecting to server e printStackTrace System exit 1 catch BlipServerAccessException e e printStackTrace System out printin Error r
51. headers sent from the client by calling either get Header or getHeaderList javax obex Operation Theoperat ion interface provides you with all the methods necessary to complete an OBEX GET or PUT operation What do we mean by complete As you can see in the following code snippet an Operation was created using the put method in ClientSession ClientSession session ClientSession Connector open connectURL Operation op session put null However the Operation is not complete until you include the object that you want to send in the case of aPUT and add some headers Following is an example of how to complete a PUT operation ClientSession session ClientSession Connector open connectURL Operation op session put null OutputStream out op openOutputStream out write Test getBytes out close Now in order to make a CREATE EMPTY operation just open and close the OutputStream without writing any data as shown here ClientSession session ClientSession Connector open connectURL Operation op session put null OutputStream out op openOutputStream out close H The easiest way to create a PUT DELETE is to call the delete method of this class javax obex ResponseCodes TheResponseCodes class contains all the valid response codes that an OBEX server can send to its client Since the OBEX request response model is very similar to that of HTTP
52. if they are equal byte getBytes Returns the byte representation of this Short Uuid object int getInt int hashCode Returns a hashCode for this Short Uuid java lang String toString Returns a String representation of this ShortUuid java lang String toString4MalSignal Class TerminalNotConnectedException public class TerminalNotConnectedException extends java lang RuntimeException Thrown by a BlipNodeHandle when a request for action is made towards a terminal which is not connected Package com ericsson blipnet api blipnode Constructors TerminalNotConnectedException TerminalNotConnectedException java lang String message TerminalNotConnectedException java lang String message java lang Throwable cause TerminalNotConnectedException java lang Throwable cause Class WapServicelndication public final class WapServiceIndication extends java lang Object implements ObexPushObject java io Serializable ThewapServiceIndication class models the WAP Service Indication This service provides the ability to send notifications to end users in an asynchronous manner Such notifications may for example be about new e mails changes in stock prices news headlines advertising reminders of for example low prepaid balance and so forth The WAP Service Indication contains a short message and a URI indicating a service The message is presented to the end user upon recept
53. int INT 2 static int INT 4 static int INT 8 static int NULL static int STRING static int U INT 1 static int U INT 16 static int U INT 2 static int U INT 4 static int U INT 8 static int URL static int UUID constructors DataElement boolean bool DataElement int valueType DataElement methods DataElement int valueType long value int valueType java lang Object value void addElement DataElement elem boolean getBoolean int getDataType long getLong int getSize java lang Object getValue void insertElementAt DataElement elem int index boolean remove Element DataElement elem Class DeviceClass constructors DeviceClass int record methods int getMajorDeviceClass int getMinorDeviceClass int getServiceClasses Class DiscoveryAgent fields static int static int static int static int static int methods CACHED GIAC LIAC NOT_DISCOVERABLE PREKNOWN boolean cancellInquiry DiscoveryListener listener boolean cancelServiceSearch int transID retrieveDevices int option RemoteDevic int searchServices i java lang String sel int attrSet UUID uuidSet RemoteDevice btDev DiscoveryListener discListener lectService UUID uuid int security boolean master boolean startInquiry int accessCode DiscoveryListener listener Interface DiscoveryListener
54. is ready exit call close onthe StreamConnectionNotifier 6 The system removes the service record from the SDDB StreamConnectionNotifier and Connector both come from the javax microedition io package the J2ME platform Listing 4 4 is a snippet of code that achieves the service registration process Listing 4 4 The Service Registration Process let s name our variables 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 localdevice LocalDevice getLocalDevice servicerecord localdevice getRecord notifier step 3 is optional step 4 this step will block the current thread until a client responds notifier acceptAndOpen the service record is now in the SDDB 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 that you need to do service registration in Bluetooth The next step is communication Communication Okay Bluetooth is a communication protocol so how do you communicate with it Well the official Java Bluetooth API gives
55. its public methods Figure 12 3 The Service Provider registers its ServiceItem with the Lookup Service Figure 12 4 The Lookup Service receives a multicast request from the Service Consumer and responds with a unicast message containing the ServiceRegistrar object Figure 12 5 The Service Consumer uses the local ServiceRegistrar object to look up services that are registered in the Lookup Service Figure 12 6 The Serviceltem requested is returned to the Service Consumer and can be used locally Figure 12 7 Once activated on the Service Consumer the Service Provider s service may communicate directly with the Service Provider device as part of the service offered Figure 12 8 In an all Bluetooth Jini federation all the devices participating in the federation must be Bluetooth enabled This federation is wireless Figure 12 9 In ahybrid Bluetooth Jini federation at least one of the devices participating in the federation must be Bluetooth enabled This federation is not necessarily wireless and the Jini Bluetooth enabled device acts as a bridge between the Jini federation and an external Bluetooth piconet Figure 12 10 The PsiNode development platform The Ericsson Bluetooth module is covered by two metal plates and is connected to the Dallas Semiconductor TINI microcontroller Appendix C Java Bluetooth Development on the PalmOS Platform Figure C 1 With the TDK Bluetooth Developer s Kit and the PalmOS emulator you can de
56. listener that will respond to OBEX requests made to the server The Benefits of the Java Bluetooth API There are two key advantages to using the official Java Bluetooth API versus a C based or native API API is independent of the stack and radio m Standardized Bluetooth API API Is Independent of Stack and Radio So what makes the official Java Bluetooth API better than a C C Bluetooth API One of the principle reasons is that the JSR 82 APlis independent of the stack and the Bluetooth hardware That gives you the ability to write applications without any knowledge of the underlying Bluetooth hardware or stack And that s essentially what Java gives you today If you write standard Java code without any native methods you can run your code on basically any hardware platform and on any OS with little or no modification Whether it s an appli cation applet midlet servlet or EJB you can code your application on one platform and deploy to another platform The Only Standardized Bluetooth API If you have a C Cbased Bluetooth SDK then you are basically at the mercy of the vendor There is no standard for a C Cbased Bluetooth SDK so each vendor is free to name functions and methods to whatever they choose Vendor A may have five profiles in its SDK and Vendor B may only have three If you want to change Bluetooth hardware or stack libraries then you ll need to rewrite your Bluetooth application and or change its functionali
57. listing 161 Baseband controller Bluetooth 183 Basic Imaging Profile 28 Basic Printing Profile 28 BCC Bluetooth Control Center 46 191 BeamTsk java listing 87 88 Blatand King Harald of Denmark 11 Blip Manager application 231 232 BlipNet 226 232 accessing external resources 228 architecture 227 232 architecture diagram 227 Blip Manager application 231 232 BlipNodes 229 230 BlipServer 227 228 BlipNet API overview 232 233 BlipNet packages 232 233 BlipNetlcons class 233 BlipNode installation 230 BlipNode unit 230 BlipNodes BlipNet 229 230 BlipServer BlipNet 227 228 BlipServerConnection class 234 BlipServerEventAdapter class 235 BlipServerEventFilter class 234 235 BlipServerEventListener class 235 BlueCore 01b CSR 183 Bluetooth vs 802 11b 1 3 as cable replacement technology 2 as a low power wireless technology 2 as a wireless communication protocol 1 basic components of 45 72 241 client server architecture 1 deployment locations 226 history of 1112 vs infrared 1 integrating with Java 33 43 integrating with Jini 252 256 integrating with JPS 104 112 with J2ME MIDP 75 96 nominal range 1 omnidirectional transmissions 1 on PalmOS platform 269 272 in small office or home office 6 for voice applications 6 7 when not to use with Java 33 34 for wireless gaming 7 in your car 7 8 Bluetooth Assigned Numbers document 52 Bluetooth certified product explained 31 Bluetooth
58. managing groups of nodes A means for session management when clients move between nodes Note Of course Class 1 Bluetooth devices have a range of 300 ft but you must realize that if the client is a Class 2 or Class 3 device like most mobile phones and PDAs then it doesn t matter if the server is a Class 1 device like some LAN access points The JSR 82 was not created to handle enterprise Bluetooth applications and doesn t provide any way to address the problems that enterprise Bluetooth applications can solve Consider the locations where Bluetooth applications will be widely deployed like shopping malls airports museums office buildings and grocery stores At a mall for instance the scaling issue is very important It s not practical to create a Bluetooth enabled information kiosk at a mall without being able to scale up to handle more than just seven active connections In order to accomplish this your enterprise Bluetooth applications will contain more than a single Bluetooth enabled node Centralized communication is an important feature in enterprise Bluetooth applications because there s no way to implement group management or session management without it For instance in a Bluetooth enabled museum exhibit there should be a way to activate or deactivate a group of nodes without disturbing the other nodes on the network Session management comes into play in a Bluetooth enabled retail location like a grocery store Without s
59. mind is why the values for the access modes are 0 10390272 and 10390323 Wouldn t it be simpler for the values to be something like 0 1 and 2 Well the codes for NOT_DISCOVERABLE LIAC and GIAC are all defined in the Bluetooth Assigned Numbers document from http www bluetooth org Each entry in the document which has more than just codes for Bluetooth discovery modes has a unique code in hexadecimal format The actual codes for LIAC and GTAC as describe in the Bluetooth Assigned Numbers document are 0x9E8B00 for LIAC and 0x9E8B33 for GIAC For your convenience these values are available to you as public constants in the DiscoveryAgent class javax bluetooth DiscoveryAgent java public static final int NOT DISCOVERABLE 0 public static final int LIAC 0x9E8B00 10390272 public static final int GIAC Ox9E8B33 10390323 public int getDiscoverable Call this method if you want to know the current discovery mode of your Bluetooth device This will obviously return an int that s either NOT_DISCOVERABLE LIAC or GIAC javax bluetooth RemoteDevice TheRemot eDevice class gives you access to a single remote Bluetooth device in the area The most commoti way to obtain a reference to a Remot eDevice is through device discovery which is covered in the next section Here are two useful methods that pertain to device management public final String getBluetoothAddress As
60. notifier acceptAndOpen As you can see it is not much different from the standard St reamConnectionNotifier and Connection used for RFCOMM server connections L2CAP Client Connections Now here s the code that a client would use in order to establish an L2CAP connection with a server L2CAPConnection L2CAPConnection Connector open url Once again it s pretty straightforward More on MTUs Now let s look at MTUs one more time in conjunction with opening connections For instance if the server cod looked like this String url btl2cap localhost 001122334455667788 9 9AABBCCDDEEFF ReceiveMTU 1024 TransmitMT 1024 The connection St ring for the client on the other hand would look something like this String url btl2cap 2E345BB78902 1055 ReceiveMTU 4096 TransmitMTU 512 As you can see the server is proposing to send data in packet sizes of 1024 bytes Since the client is able to receive data packets four times that size the negotiated connection will have a packet data size of the lowest common denominator 1024 On the other hand the client wants to send its datain packets of 512 bytes The server is able to handle that packet size with no problem at all and the negotiated connection will be 512 byte packets Now let s take a brief look at the two classes used in order to create L2CAP connections and some of their methods javax bluetooth L2C APConnection This interface is just
61. of the file would look something like this BT LAN ACCESS MODE automatic IP ASSIGNMENT automatic INQUIRY CYCLE 15 in seconds PPP USER ID myName PASSWORD myPassword AUTHENTICATION PAP CHAP preferred methods The Micro BlueT arget would then constantly search in this case every 15 seconds for appropriate devices an provide them with network access Note Now it s nice to know that the Micro Blue Target has the built in capability to function as a wireless nel access point but what type of effort would be involved if you wanted to develop that functionality your First of all since the JSR 82 doesn t provide any foundational classes to write apps according to the L Access Profile then you ll need to implement it on your own According to the LAN Access Profile por the Bluetooth specification data terminals i e phones PDAs etc are supposed to authenticate witl LAN access point using the PPP protocol After that the data terminal will be assigned a dynamic IP address an IP gateway and a DNS server for Internet name resolution You re not out of the woods y that s where a majority of the effort should exist L2CAPEcho Example L2CAPEcho is a very simple example that will demonstrate communication between two Micro BlueTarget devi This is the first example involving two Micro BlueTarget devices and this is the kind of example that you want to just to make sure you can get two devices talking
62. static int OBEX HTTP PAYMENT REQUIRED static int OBEX HTIP PRECON FAILED static int OBEX H P_PROXY AUTH static int OBEX HTIP REQ TOO LARGE static int OBEX HTTP RESET static int OBEX HTTP_ SEE _ OTHER static int OBEX HTTP TIMEOUT static int OBEX H P_UNAUTHORIZED static int OBEX_HTTP_UNAVAILABLE static int OBEX_HTTP_UNSUPPORTED_TYPE static int OBEX_HTTP_USE_PROXY static int OBEX_HTTP_VERSION Class ServerRequestHandler constructor protected ServerRequestHandler methods HeaderSet createHeaderSet long getConnectionID void onAuthenticationFailure byte userName int onConnect HeaderSet request HeaderSet reply int onDelete HeaderSet request HeaderSet reply void onDisconnect HeaderSet request HeaderSet reply int onGet Operation op int onPut Operation op int onSetPath HeaderSet request HeaderSet reply boolean backup boolean create void setConnectionID long id Interface SessionNotifier methods javax microedition io Connection acceptAndOpen ServerRequestHandler handler javax microedition io Connection acceptAndOpen ServerRequestHandler handler Authenticator auth Appendix C Java Bluetooth Development on the PalmOS Platform The purpose of this appendix is to demonstrate how to get started using the Impronto Developer Kit 1 0 for PalmOS the Palm DK Note For more updated information please consult the Palm DK user guides Supp
63. taken in the preparation of this work neither the author nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work The source code for this book is available to readers at http www apress com in the Downloads section First and foremost dedicate this book to the Lord Jesus Christ without whom I could not have written this book also dedicate this book to my loving wife Schrell and my two wonderful children Lydia and Bruce Jr Bruce Hopkins Dedicated to my parents Prof Antony Mampilly and Prof Kochurani Mampilly Ranjith Antony About the Authors Bruce Hopkins is a 6 year Java veteran with experience in distributed computing and wireless networking He has an electrical and computer engineering degree from Wayne State University in Detroit and has interest in robotics microcomputing and electronics He has worked in Java since JDK 1 0a and his research studies include distributed computing clustering encryption and pervasive computing He currently works as an independent consultant in the Metro Detroit area Ranjith Antony earned his bachelor of technology degree in computer engineering from the College of Engineering Chengannur Kerala India an institute affiliated with Cochin University of Science and Technology He became a lecturer in the Department of Computer Engineerin
64. than use a trademark symbol with every occurrence of a trademarked name we use the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark Technical Reviewer Andrew Stringer Editorial Directors Dan Appleman Gary Cornell Simon Hayes Karen Watterson John Zukowski Assistant Publisher Grace Wong Project Manager and Development Editor Tracy Brown Collins Copy Editor Ami Knox Compositor Impressions Book and Journal Services Inc Artist and Cover Designer Kurt Krames Indexer Valerie Robbins Production Manager Kari Brooks Manufacturing Manager Tom Debolski Distributed to the book trade in the United States by Springer Verlag New York Inc 175 Fifth Avenue New York NY 10010 and outside the United States by Springer Verlag GmbH amp Co KG Tiergartenstr 17 69112 Heidelberg Germany In the United States phone 1 800 SPRINGER email lt orders springer ny com gt or visit http www springer ny com Outside the United States fax 49 6221 345229 email lt orders springer de gt or visit http www springer de For information on translations please contact Apress directly at 2560 9th Street Suite 219 Berkeley CA 94710 Phone 510 549 5930 fax 510 549 5939 email lt info apress coms gt or visit http www apress com The information in this book is distributed on an as is basis without warranty Although every precaution has been
65. the Bluetooth adopted protocols like WAP Take a look at Figure 7 1 to see where OBEX fits in the Bluetooth and IrDA protocol stacks OBEX ir0BEX sD RFCOMM Tiny Transport IAS Protocol L2CAP Infrared Link Manager HCI Infrared Link Protocol Link Manager 3 Link Controller Figure 7 1 OBEX is called IrOBEX in the IrDA protocol stack In the Bluetooth specification OBEX is the underlying protocol that is used to implement the following Bluetooth profiles a Generic Object Exchange Profile Object Push Profile Synchronization Profile a File Transfer Profile Basic Imaging Profile Basic Printing Profile Note Did you realize that the official Java OBEX implementation was named javax obex and not javax bluetooth obex lt was named javax obex because the JSR 82 designers knew that if structured correctly the OBEX libraries would be the same regardless of the underlying transmission protocol also known as the bearer or the transport So you can use the classes in the javax obex package to send objects between any device that implements the official Java OBEX API The JSR 82 provides guidelines on how to use OBEX over Bluetooth IR and TCP IP connections The OBEX protocol has a simple client server architecture OBEX clients get objects from and put objects onto OBEX servers OBEX servers wait around for incoming requests from clients The OBEX definition can be summarized i
66. the Bluetooth specification for more details on how to browse for services javax bluetooth DiscoveryListener Our good ol buddy DiscoveryListener which helped us to discover devices comes back to help us discov services on remote Bluetooth devices public void servicesDiscovered int transID ServiceRecord servRecord If you use the DiscoveryAgent searchServices method which accepts a DiscoveryListener th this method is called by the JVM when services are discovered on the remote device The transaction ID and a1 array of ServiceRecord objects are provided to this method With a ServiceRecord in hand you can do plenty of things but you would most likely want to connect to the Remot eDevice where this ServiceRecord originated String connectionURL servRecord i getConnectionURL 0 false javax bluetooth ServiceRecord ServiceRecord objects are representations of individual entries in the SDDB As you may remember the SDDB is the central repository of service records for a Bluetooth device javax bluetooth DataElement As we continue to break down the anatomy of service discovery let s now examine the DataElement object EachServiceRecord object in the SDDB is made up of attributes All attributes are stored as DataElement objects ADataElement object can be from any of the following Integers Booleans Strings a UUIDs Sequences of the preceding values Be sure to take another look at Figures 4 1 throu
67. the URL c anywhere else Assigning and entering the PINs on both the client and server are handled by the BC Bluetooth Server Authorization Bluetooth servers can request that only authorized devices connect and use a particular service These authori devices are called trusted devices Servers can require that clients be authorized by setting the authorize parameter to t rue in the connection shown here F EFF authorize tr String url btspp 02AB45AC35DF 00112233445566778899AABBCCDD Authorization requires authentication so the following line of code is more descriptive of what s actually going o String url btspp 02AB45AC35DF 00112233445566778899AABBCCDDEEFF authenticate true authorize true However if you explicitly set authenticate to false and authorize to true then the system will throw a BluetoothConnectionException If authorization was not specified in the connection URL the server can the client to be authorized by calling the authorize method of the RemoteDevice class as follows get an instance of the RemoteDevice if we don t already have it assume that we have an active Connection object named conn RemoteDevice remoteDevice RemoteDevice getRemoteDevice conn remoteDevice authorize conn Whether the connection is established or not the server can check to see if the client is a trusted device by call isTrustedDevice method of the RemoteDevice cla
68. the devices be TCP IP based the Bluetooth devices in an all Bluetooth Jini federation would be connecting with either of the following TCP IP based Bluetooth profiles Dial Up Networking Profile a LAN Access Profile Personal Area Networking Profile Note Invariably a manufacturer could make an all Bluetooth Jini device without providing any of the preceding Bluetooth profiles in its product For instance the manufacturer can satisfy the TCP IP requirement by simply implementing the BNEP protocol The major drawback however is that those devices will be totally incompatible with devices from other manufacturers After the piconet has been established and the IP addresses have been assigned the Jini federation can be formed At this point this federation is just like any other Jini federation If other Bluetooth devices want to join the federation they must first join the piconet obtain an IP and then join the Jini federation Since the IP network is running over Bluetooth this federation is wireless An example of an all Bluetooth Jini federation is shown in Figure 12 8 Lookup Service N N Service Consumer Service Provider 8 8 lt m x N Figure 12 8 In an all Bluetooth Jini federation all the devices participating in the federation must be Bluetooth enabled This federation is wireless Hybrid Bluetooth Jini Federation In a hybrid Bluetooth Jini federation one or more devices are Bluetooth enabled Note h
69. the qualification process if prequalified Bluetooth materials i e stacks and radios are used in their products However if you want to use that really cool looking Bluetooth logo on your products then you need to join the SIG Once testing has been completed and if your device passes the tests it will be listed on the Bluetooth Qualification Web site http aualweb bluetoothsig org Most companies will postpone announcing their new Bluetooth enabled product until it has been certified so check that site often to see who s doing what in Bluetooth Summary In this chapter you learned all about Bluetooth devices and you found out what they look like By now you should also know about the role of the Bluetooth protocol stack and how it interacts with your Bluetooth hardware You should take away from this chapter a finite knowledge of Bluetooth profiles and you should know the purpose that they serve Finally you should be aware of the difference between piconets and scatternets and you should know what it takes to get a Bluetooth device certified Great You now should have a good understanding of how the Bluetooth protocol works In the next chapter we ll see what happens when we throw in Java Chapter 3 Before You Get Started Okay now that you know the ins and outs of Bluetooth you re probably eager to find out how to integrate Bluetooth with Java Well this chapter is all about doing just that But wait Before you learn a
70. transfer client 131 134 File transfer example JSR 82 OBEX API 127 136 File Transfer Profile 27 File transfer server 127 131 Fixed wireless commercial system 182 Fixed wireless consumer system 181 Fixed wireless device explained 181 Fixed wireless system creating 207 223 Flash disk 188 Flash memory 187 189 Flat file system RMS as 79 Fossil Wrist PDA with Palm OS 4 1 9 FTClient java listing 132 134 FTServer java listing 128 130 Future Bluetooth devices 8 9 Index G Gaming wireless Bluetooth for 7 playing in restaurant lobby 9 Gate count CPU 183 GCF Generic Connection Framework 42 80 105 Generic Access Profile 24 28 51 229 Generic Object Exchange Profile 27 GET operation OBEX 121 123 131 GetAppProperty method of MIDlet 144 GetBluetoothAddress method 51 53 GetConnection method BlipServer object 234 GetDiscoverable method 53 GetDiscoveryAgent method 56 GetEventFilter method 234 GetFriendlyName method 53 GetLocalDevice method 51 GetMajorDeviceClass method 53 GetMinorDeviceClass method 53 Grade school environment 232 Grocery store Bluetooth device tracker 233 240 Grocery store environment 226 233 240 Index H Hands Free Profile 28 Hardcopy Cable Replacement Profile 28 97 HCI Host Controller Interface 20 187 HeaderSet interface javax obex 117 118 122 123 265 266 HeaderSet object 131 135 Headset Profile 26 HID Human Interface Device
71. values for Bluetooth profiles 62 for Bluetooth protocol layers 61 Index V Vending machine Bluetooth enabled 181 Virtual serial port communication protocol SeeRFCOMM Voice applications 6 7 33 34 Index Ww WAP Wireless Access Protocol WAP over Bluetooth 229 Windows 2000 Device Manager 25 Windows CE NET 185 Wireless com munication protocol Bluetooth as 1 1 229 Wireless dial up networking 5 Wireless embedded systems 179 224 Wireless LAN 802 1b vs Bluetooth 1 3 Wireless Network Access Point 191 192 Wireless serial port SeeRFCOMM Wireless System Monitor example 207 223 client options 223 224 server setup 208 223 List of Figures Chapter 1 Introducing Bluetooth Fiqure 1 1 The short antennae on HP iPAQ 5400 series Pocket PC allows it to communicate via Bluetooth and 802 1 1b For added security this model also includes a fingerprint reader Figure 1 2 The Bluetooth enabled Nokia N Gage wireless gaming system Figure 1 3 Although the Fossil Wrist PDA doesn t contain any Bluetooth hardware it does come preloaded with a Bluetooth enabled OS the Palm OS 4 1 Palm OS is a registered trademark of Palm Inc Chapter 2 Bluetooth 1 1 Fiqure 2 1 The 3COM USB Bluetooth module Figure 2 2 The CSR BlueCore 1 This single chip solution includes a microprocessor RAM I O controller and Bluetooth implementation in a single package This is most likely the smallest radio that you ve ever seen
72. values for protocols and profile services can be seen in the Bluetooth Assigned Numbers document Table 4 3 Common UUID Values for Bluetooth Protocol Layers PROTOCOL UUID DECIMAL UUID HEXADECIMAL SDP 1 0x0001 RFCOMM 3 0x0003 L2CAP 256 0x01 00 HTTP 12 0x000C FTP 10 0x000A TCP 4 0x0004 IP 9 0x0009 UDP 2 0x0002 BNEP 15 0x000F OBEX 8 0x0008 TCS BIN 5 0x0005 Table 4 4 Common UUID Values for Bluetooth Profiles PROFILE SERVICE NAME UUID UUID DECIMAL HEXADECIMAL Serial Port SerialPort 4353 0x1101 Dial up Networking LANAccessUsingPPP 4354 0x1102 Dial up Networking DialupNetworking 4355 0x1103 Object Push OBEXObjectPush 4357 0x1105 Object Push OBE FileT ransfer 4358 0x1106 Cordless Telephony CordlessTelephony 4361 0x1109 Audio Video Control A V_RemoteControl 4366 0x110E Profile Intercom Intercom 4368 0x1110 Fax Fax 4369 Ox11 11 Generic Access Headset 4360 0x1108 Generic Access HeadsetAudioGate way 4370 0x1112 Handsfree Handsfree 4382 0x111E Handsfree HandsfreeAudioGateway 4383 0x111F Basic Printing BasicPrinting 4386 Ox1122 Basic Printing PrintingStatus 4387 0x1123 Hard Copy Cable HardCopyC ableReplacement 4389 0x1125 Replacement Hard Copy Cable HCR_Print 4390 Ox1126 Replacement Hard Copy Cable HCR Scan 4391 Ox1127 Replacement Human Interface HumaninterfaceDeviceService 4388 Ox11 24 Device Generic Ne
73. 007e3ba4780f 0065ca98bd2e This application starts off by calling the method initBlipServerConnection inthe constructor In turn initBlipServerConnection obtains a BlipServerConnection object by calling the static method getConnection from the BlipServer class The parameters to this method include the user name and password that you ve created as well as the hostname of the BlipServer BlipServer getConnection Tracking Tracy localhost Afterwards a BlipServerEventFilter is created by calling the getEvent Filter method BlipServerEventFilter blipServerEventFilter getEventFilter discoverBlipNodeGroup terminalsToTrac Finally we re going to add an event listener to the BlipServerConnectioninstance by calling its addEventListener method blipServerConnection addEventListener new TrackingEventListener blipServerEventFilter TheaddEventListener method requires a BlipServerEventListener and optionally a BlipServerEventFilter At this point we already have an instance of a BlipServerEventFilter on hand so we create a new instance of our inner class TrackingEventListener TrackingEventListene a subclass of BlipServerEventAdapter which in turn is an implementation of BlipServerEventListener When Bluetooth devices are detected the events are passed to the inner class and the inner class then prints on the command line what s going on The code
74. 26 127 SessionNotifier class 127 Javax print package 99 101 See also JPS Javax print attribute 99 Javax print attribute standard 99 Javax print Doc interface 100 Javax print DocFlavor 100 Javax print event package 99 Javax print PrintService object 100 Javax print PrintServiceLookup object 101 Javax print SimpleDoc object 100 101 JCP Java Community Process 34 38 Jini 241 258 Discovery Service 244 events 245 how it works 245 253 integrating with Bluetooth 251 255 Join protocol 244 Leasing Service 244 Lookup Service 243 247 Lookup Service discovery 245 247 Service Consumer lifecycle 249 251 Service Provider lifecycle 245 249 Serviceltem object 245 248 249 252 253 ServiceRegistrar object 247 248 249 250 ServiceT emplate object 249 solving distributed computing problems 242 transactions 245 Jini Bluetooth enabled device 256 257 Jini federation 243 255 entities in 245 functionality of members in 243 joining 24 7 249 Jini network technology 242 245 JMatos PsiNaptic 254 Join protocol Jini 244 JPS Java Print Service 97 113 architecture 99 attributes 99 creating a Bluetooth Print Server with 97 113 creating a document 100 101 creating a print job and printing 101 102 documents 99 101 event model 99 identifying the data format 100 integrating with Bluetooth 104 112 listening for print status updates 102 overview 98 99 relationship between printer and client 98 searching for a
75. 35DF 001122334455667788 9 9AABBCCDDEEFF encrypt true Encryption requires authentication so the following line of code is more descriptive of what s actually going on String url btspp 02AB45AC35DF 001122334455667788 9 9AABBCCDDEEFF authenticate true encrypt true However if you explicitly set authenticate to false and encrypt to true then the system will throw a BluetoothConnectionException If encryption was not specified in the connection URL the server can la encrypt the transmission by calling the encrypt method of the RemoteDevice class as shown here get an instance of the RemoteDevice if we don t already have it assume that we have an active Connection object named conn RemoteDevice remoteDevice RemoteDevice getRemoteDevice conn remoteDevice encrypt conn true now that the sensitive information has been transmitted turn off encryption and send the vest of the data unencrypted for better performance remoteDevice encrypt conn false Client Encryption Bluetooth clients can also require that their communication with their servers be encrypted by setting the ener parameter to t rue in the URL as demonstrated here String url btspp 02AB45AC35DF 001122334455667788 9 9AABBCCDDEEFF encrypt true The following line of code is also harmless String url btspp 02AB45AC35DF 001122334455667788 9 9AABBCCDDEEFF authenticate true encrypt true
76. 9200 57600 38400 9600 115200 ConnectionTable REFUSE ROLE SWITCH ERVICE LEVEL MODE 2 le new ESC ESample pin LalIFHciT ansport is a simple UART connection F vice D F iTranspor Human readable form o ht put bluetooth device iTransport Human readable form o put blue E D COO LUeTOO LUeTOO LUeTOO LUeTOO LUeTtOO LUeETOO TOTO onion OOO COO 8 L uetoo E D COO LUeTOO LUeTOO ExternalSecurityControll VICE_1 new SeriallFHciTransport devicelSerialPort devicelBaudRate th nam devic e DEVIC nam E1 NAM E new SerialIFHciTransport device2SerialPort device2BaudRate th tooth device nam devic e DEVIC nam E2 NAM E h api version h Wren Integer toString securityMode Integer toString DATA MTU devices max 7 connected inguiry true connected page true connected inguiry scan true connected page scan true master switch true sd trans max Integer toString SDP_CLI sd attr retrievable max 64 security mode l2cap receiveMTU max connected ENT_ THREADS oJ JJ roperties Entity getEsce myE
77. AC catch BluetoothStateException e System err printin Failed to start service System err printin BluetoothStateException e getMessage return EEY start the SPP server with a fictional UUID Server StreamConnectionNotifier Connector open btspp localhost FFEEDDCCBBAA99887766554433221100 catch IOException e System err printin Failed to start service System err printin IOException e getMessage return System out println Starting SPP Server while true accept connections only if we are not yet connected if SPP2COMM bluetoothport null EEY wait for incoming client connections blocking method SPP2COMM bluetoothport Server acceptAndOpen catch IOException e System out printin IOException e getMessage try Thread sleep 1000 catch Exception e Client Options Once you get data feeding the Micro BlueTarget and have sPP2COMM running on it then you re all set from the server s point of view you have created a fixed wireless system Now on the client side of things you have a fev options Let s say that the vendor of the PLC makes a program to read and interpret the data from the PLC wh connected serially of course You really don t need to use the sPP 2COMM in client mode at all all you need to Bluetooth enable your laptop and pair it with
78. AL DETECTED Indicates that a terminal was detected in inquiry static int TERMINAL_LINK_ESTABLISH_FAILI El oO Indicates a failed attempt to establish a Bluetooth link to a terminal T static int TERMINAL LINK ESTABLISHED Indicates that a Bluetooth link to a terminal has been established static int TERMINAL LINK LOST Indicates that a Bluetooth link to a terminal has been disconnected static int TERMINAL SESSION CREATE FAILED Indicates a failed attempt to create a session with a terminal static int TERMINAL SESSION CREATED Indicates that a session has been created with a terminal static int TERMINAL SESSION REMOVED Indicates that a session with a terminal has been removed Methods boolean equals java lang Object obj Returns true if content of object is equal to this BluetoothAddress getBlipNodeID Returns the Bluetooth device address of the BlipNode to which this event is related int getEventClass Returns the event class of this event int get EventID Returns the ID of this event java lang String getMessage Returns the message associated with this event if any int hashCode java lang String toString Returns a String representation of this event Interface InquiryResultEvent public interface InquiryResultEvent extends ConnectionEvent An
79. Bluetooth development on 269 272 running versions of 138 Palm Source emulator 138 PAN Personal Area Networking Profile 26 PasswordAuthentication class javax obex 266 PC to peripherals replacing cable between 5 PCs connecting two 5 PDA to phone data transfer 3 4 PDAs Bluetooth enabled 4 service discovery process for 60 Peripherals connected wirelessly 5 6 Persistent storage RMS for 79 80 Personal area networks 30 31 Personal networks PC to PC 5 PIC family microcontrollers 184 Piconet Browser example application 88 96 displaying Bluetooth devices in the area 90 displaying remote device services 91 initial screen for 89 PiconetMIDlet java listing 91 95 Piconets Bluetooth 30 31 PIN personal identification number codes 156 PLC Programmable Logic Controller 207 Point to point device communication 15 POSE PalmOS emulator 140 Power classes of Bluetooth devices 16 17 Power user 6 PPP protocol 192 PREKNOWN device explained 56 57 Print attributes JPS 99 Print job creating in JPS 101 1 02 Print server client submitting a file to 109 creating with JPS API 97 113 Print services explained 100 searching for in JPS 101 Print status updates in JPS 102 Print method 101 Printer adapter Bluetooth 97 Printers Bluetooth 20 100 PrintFile method 105 Printing in JPS 101 102 wireless 5 6 PrintJobListener interface 102 PrintService object 100 101
80. Bluetooth for J ava by Bruce Hopkins and Ranjith Antony ISBN 1590590783 Apress 2003 352 pages The authors of this text describe how to develop wireless Java applications using Bluetooth for a variety of platforms This includes an API overview of the Java library development of Bluetooth based services highlights of security concerns and more Table of Contents Bluetooth for Java Introduction Chapter 1 Introducing Bluetooth Chapter 2 Bluetooth 1 1 Chapter 3 Before You Get Started Chapter 4 Understanding the Java Bluetooth API Chapter 5 Bluetooth with J 2ME MIDP Chapter 6 Creating a Bluetooth Print Server with JPS API Chapter 7 Java and OBEX Chapter 8 Using a Bluetooth Simulator Chapter 9 Bluetooth Security Chapter 10 Wireless Embedded Systems with the Micro BlueTarget Chapter 11 Enterprise Bluetooth Applications with the Ericsson BlipNet Chapter 12 Bluetooth and Jini Appendix A javax bluetooth Appendix B javax obex Appendix C Java Bluetooth Development on the PalmOS Platform Appendix D BlipNet 1 1 API Index List of Figures List of Tables List of Listings List of Sidebars Back Cover Bluetooth is a technology for wireless communication It is similar in functionality to the way laptops connect to the Internet from home office but is typically used for short burst communications instead of a continuous connection Because of this difference Bluetooth is more typically found supported in wi
81. COMM java is a dual purpose application that you could run on a Micro BlueTarget in order to read the di from its serial port and transmit it wirelessly When the Micro Blue Target receives data coming in from its COMI will go into server mode and create a Serial Port Profile server and pipe the data from the COMM port to its S Port Profile port This same code could also be run on a JSR 82 enabled client in order to collect the data from the Micro BlueT Since the client isn t collecting data from its serial port it will automatically go into client mode and create a Se Port Profile client When the client receives data it will try to pipe the data to its native serial port The code for SPP2COMM java is shown in Listing 10 3 Listing 10 3 SPP2COMM java import java lang import java io import java util import javax microedition io import javax bluetooth public class SPP2COMM implements DiscoveryListener The connection to the serial port static StreamConnection serialport null The Input Output streams to the local serial port static OutputStream ser_out null static InputStream ser_in null The Bluetooth connection to the peer devic static StreamConnection bluetoothport null The Input Output streams to the Bluetooth connection static OutputStream bt_out null static InputStream bt_in null The DiscoveryAgent for the local Bluetooth device privat
82. Class ClassOfDevice public final class ClassOfDevice extends java lang Object implements java io Serializable TheclassofDevice class models a class of device This is a 24 bit unsigned integer often written in hexadecimal Objects of the ClassOfDevice class are im mutable once created they cannot change This class provides the equals and hashCode methods for use in connection with the Collection classes Package com ericsson blipnet api Bluetooth Fields static java lang String AV static java lang String AV_CAMCORDER static java lang String AV_CAR_AUDIO static java lang String AV_GAMING_TOY static java lang String AV_HANDS_FREE static java lang String AV_HEADPHONES static java lang String AV_HEADSET static java lang String AV_HIFI static java lang String AV_LOUDSPEAKER static java lang String AV_MICROPHONE static java lang String AV_PORTABLE_AUDIO static java lang String AV_SET_TOP_BOX static java lang String AV_SHORT static java lang String AV_VCR static java lang String AV_VIDEO_CAMERA static java lang String AV_VIDEO_CONF static java lang String AV_VIDEO_DISPLAY static java lang String AV_VIDEO_MONITOR static java lang String BLIPNODE_CLASS_OF_DEVICE static java lang String COMPUTER static java lang String COMPUTER_
83. ClientSession object connect method 131 create HeaderSet method 122 disconnect method 132 setPath method 135 Com ericsson blipnet api packages 232 233 Communication 67 72 multipoint 16 point to point 15 CONNECT operation OBEX 121 131 Connect method of ClientSession object 131 Connection class javax microedition io 122 Connection sharing laptop to phone 5 Connection URL String 128 authenticate parameter 156 157 162 authorize parameter 158 encrypt parameter 161 162 174 177 and the SDDB 130 Connections Bluetooth device 15 16 defined 68 and sessions 68 Connector class 66 Connector object open method 64 69 80 130 ConnectT oClientAndPrint method 105 CONTINUE response code OBEX 121 125 Controllers SeeBluetooth devices Cordless phone Bluetooth 21 27 Cordless Telephony Profile 27 CPU gate count 183 CREAT E EMPTY operation OBEX 123 Create HeaderSet method 122 CreatePrintJob method 101 CSR baseband controller 187 CSR BlueCore 1 radio 14 Index D Data format identifying with JPS 100 Data security SeeSecurity Data terminal authentication 192 DataElement class javax bluetooth 59 60 65 260 Debugging with Bluetooth simulator 137 153 Decryption 177 178 Deployment locations for Bluetooth applications 226 Development environment setup checklist 81 Device classes Bluetooth major and minor 54 55 Device communication types multipoint 16 point
84. DESKTOP static java lang String COMPUTER_HANDHELD static java lang String COMPUTER_LAPTOP static java lang String COMPUTER PALM SIZED static java lang String COMPUTER SERVER CLASS static java lang String COMPUTER SHORT static java lang String COMPUTER WEARABLE static java lang String IMAGING static java lang String IMAGING CAMERA static java lang String IMAGING DISPLAY static java lang String IMAGING PRINTER static java lang String IMAGING SCANNER static java lang String IMAGING SHORT static java lang String LAN ACCESS POINT static java lang String LAN ACCESS POINT FIFTH static java lang String LAN ACCESS POINT FIRST static java lang String LAN ACCESS POINT FOURTH static java lang String LAN ACCESS POINT FULLY static java lang String LAN ACCESS POINT NO SERVICE static java lang String LAN ACCESS POINT SECOND static java lang String LAN ACCESS POINT SHORT static java lang String LAN ACCESS POINT SIXTH static java lang String LAN ACCESS POINT THIRD static java lang String PERIPHERAL static java lang String PERIPHERAL COMBO static java lang String PERIPHERAL DIGITIZER static java lang String PERIPHERAL GAMEPAD static java lang String PERIPHERAL JOYSTICK static java lang String PERIPHERAL KEYBOARD static java lang String PERIPHERAL POINTING DEV static java lang String PERIPHERAL
85. Data getBytes connection send data try Thread sleep 10 catch Exception e while true byte datax new byte 1000 while connection ready try Thread sleep 1 catch InterruptedException ie connection receive datax System out printlin Data received at the Client Side new String datax ff connection close catch Exception ioe loe printStackTrace end of else if Td When a device is discovered it is added to the remote device tabl Tf public synchronized void deviceDiscovered RemoteDevice btDevice DeviceClass cod device count btDevice System out printlin New Device discovered btDevice getBluetoothAddress When a service is discovered in a particular device and the connection URL is not null then the thread that is waiting in the main is notified public synchronized void servicesDiscovered int transID ServiceRecord servRecords records new ServiceRecord servRecords length records servRecords for int i 0 i lt servRecords length i int atrids servRecords i getAttributeIDs String servName String DataElement servRecords i getAttributeValue 0x100 getValue System out printin Service Name servName connectionURL servRecords i getConnectionURL 1 true System out printin Connection url connectionURL if connectionURL null synch
86. Disconnects the specified terminal from this BlipNode if it is connected void establishLink BluetoothAddress terminalID ClassOfDevice terminalCOD Attempts to establish a link to the specified terminal void establishLink PageData p Attempts to establish a link to the terminal specified in the paging data void exchangeBusinessCards BluetoothAddress terminalID Initiates a business card exchange between the specified terminal and the BlioNode if the terminal is connected to the BlipNode Link getActiveLinks Returns alist of links that are currently active on the BlipNode BluetoothAddress getBlipNodeDenyList Retrieves a list of terminals in this BlipNode s deny list BluetoothAddress getBlipNodelID Returns the Bluetooth device address of the BlipNode connected to this handle void pullBusinessCard BluetoothAddress terminalID Attempts to pull the business card from the specified terminal void push ObexPushObject pushObject BluetoothAddress terminalID Pushes the specified object to the specified terminal if it is connected to the BlipNode void push ObexPushObject pushObject BluetoothAddress terminalID ObexProgressListener listener Pushes the specified object to the specified terminal if it is connected to the BlipNode void pushBusinessCard BluetoothAddress terminalID Pushes this BlipNode s business card to the specified terminal if the terminal is connected to the BlipNode void
87. DiscoveryAgent GIAC this synchronized this this wait Once the Device inquiry is completed it starts searching for the required service Service search is done with the given uuid After starting each search it waits for the result If the connection URL is null i e if No service Records obtained then it continues search in the next device detected int attrSet 0 3 4 0x100 UUID uuids new UUID 1 uuids 0 new UUID 1111 true System out println nSearching for Service n for int i 0 i lt count itt int transactionid discoveryAgent searchServices attrSet uuids device i this if transactionid 1 synchronized this this wait if connectionURL null break catch Exception ie ie printStackTrace If the URL of the device begins with btl2cap then we call the getConnection method which establishes a connection with the L2CAPServer and returns it Connection returned is of type L2CAPConnection A piece of raw data is being sent over L2CAP if connectionURL null System out printin No service available Poke Nd else if connectionURL startsWith btl2cap try L2CAPConnection connection getconnection System out printin nConnection established to the remote device n String strData This is the Data From Client Application to Server Application byte data str
88. Figure 12 4 The Lookup Service receives a multicast request from the Service Consumer and responds with a unicast message containing the ServiceRegistrar object The Service Consumer device makes a number of periodic multicast requests When a Lookup Service receives a request it responds with a simple message that contains its ServiceRegistrar object At this point the Service Consumer is part of the federation With the ServiceRegistrar in hand the Service Consumer can use its lookupmethods to look for useful services Thelookup methods of the ServiceRegistrar object require a ServiceTemplate object as an argument This template may contain nothing more than an array of class types It s that simple You get back either the service object itself or a special object ServiceMatches containing all the services that matched your template This process is illustrated in Figures 12 5 and 12 6 Lookup Service K f Serviceltes Request Servicelten Service Consumer Service Provider ServiceRegistrar Serviceltes up services Figure 12 5 The Service Consumer uses the local Service Registrar object to look up services that are registered in the Lookup Service lockup Service Servicelten Service Provider N Servicelten Service Consumer Servicelten Servicelten k N Figure 12 6 The Serviceltem requested is returned to the Service Consumer and can be used locally Note T
89. HREADS 4 Oxffff ELS EP_CHANNI AX IN L2CA 4 P BUFFERS 32 SDP_THREAD _ TIMEOUT 1200 py fe ta st in BLUETOOTH_ ic String D VENT_TIMEOUT 00 180000 ittle Devicel e String D EVICE1 NAME EVICE2 NAME ittle Device2 ta ta in in EVICE1_IP EVICE2 IP ETMASK tatic ta ELS in in OADCAST 0x0al10101 0x0al10102 OXFFFFFFOO OxOallOlFF ff ADs T7015 01 10 17 01 02 255 2552950 10 17 01 255 T_U UID Sdp UUID_PANU n O wW 200 H R S tatic in RC_U Hashtable h private String pin 123 HciTranspor F T Ha String devicelSeria IPOrt String device2SerialPort UID Sdp UUID GN xternalSecurityControlEntity myEsce heiTransport ll COM COM ll int device LNE int int device roleSw securi 1BaudRate 2BaudRate itch Hei tyMode S DeviceProperties int device ht my n T B sce Ser if de he else he N ct pu pu pu pu pu pu pu pu pu pu pu LO OE oer E or T Li i DP Pr De E ct EA A A A A A A AA A A testP return private vo arts E3 TERS th i ge Bs ca Ga th if ge ew Hashtab 19200 38400 57600 9600 115200 1
90. Hep New Device Chen Elit Device Bluctoot Address Save Device Friendly Name aE AE Connectatie Quit Device Class Miscellanpeue No minor device Positioning Hetweorkang Rendering Figure 8 3 Creating a new Bluetooth device in the Simulator Console is pretty simple The Impronto Simulator then gives you the option to set other properties for your simulated Bluetooth device su the address the connectable mode the friendly name and the device class Figure 8 4 shows a cell phone be configured in the Simulator Console See ipj xj Hie Hevce comguwe Heip Btuvtouth Addiess 02345078170 Friereity Name mydewce Connectable r Device Clase Prone Coulter Networking capturing Object Transtor Autio 5 Devices 7 Telephony information Service Classes Discovery Moda Mot discoverable Secwity Modo Gonoral discovorabto Sam Ct t ted discoverate Figure 8 4 Configuring a cell phone in the Simulator environment Since the friendly name of the device is mydevice the Console will generate a file named mydevice xml in config directory The contents of mydevice xml are shown in Listing 8 1 Listing 8 1 mydevice xml lt device bluetoothAddress 01234567e012 friendlyName mydevice isConnectable true deviceClass Phone Cellular serviceClasses Audio Telephony discoveryMode Not discoverable securityMode Never enforce security gt lt device gt Running an Application in the Simul
91. I in order to create wireless applications The Basic Components of a Bluetooth Application The basic components of any Bluetooth application consist of the following items a Stack initialization Device management a Device discovery a Service discovery a Service registration Communication The Java Bluetooth specification adds a special component to the mix called the Bluetooth Control Center BCC We ll talk about the BCC in the next section because in some vendor implementations stack initializatio is handled through the BCC The Bluetooth Control Center The Bluetooth Control Center is an awkward beast due to its ambiguity It is required to exist in a JSR 82 compliant implementation but there are no guidelines in the official Java Bluetooth specification about how it should be implemented One vendor could implement the BCC as aset of Java classes and another vendor could implement it as a native application on the Bluetooth host But no matter how it is implemented it is an integral part of your security architecture because the BCC defines device wide security settings for your Bluetooth device Now for the most part if you are working with a JSR 82 compliant Java Bluetooth development kit within your development environment then the BCC will probably be implemented as one or more Java classes But because the BCC is vendor specific the classes that form the BCC will not have a javax bluetooth packag name they will be
92. Ids in the group intin Specify the group name as first input parameter 5 System out println gt Tracking MyGroup System out p ry intln Thereby the BlipNodes specified in the BlipManager in the group MyGroup will be used These BlipNodes must be System out printin configured as Inquiry Only BlipNodes Use at least two BlipNodes in the group System out printin When no Terminal Ids are specified all discoverable devices will be tracked System out printin N System out println If only specific terminal is to be tracked the Terminal Ids can be specified after the group name e g System out printin gt Tracking MyGroup 001122334455 000102030405 System out printin Thereby the same BlipNodes as above be used for tracking System out printin and only the terminals with Ids 001122334455 000102030405 will be tracked terminal list can be continued System out printin System out printin In Bli System out printin Appli ipManager a username password pair must be ined for the Tracking application Under BlipServer Properties 1 r cations Create a new user with name password Tracking Tracking System exit 1 public static void main String args Must specify at least a BlipNode Group LE args length
93. J2ME Java 2 Micro Edition platform 42 186 MIDP 75 96 overview of 75 J2ME Profiles 75 vs Bluetooth profiles 29 30 diagram of 76 J2ME Wireless Toolkit 78 J2SE platform 42 with BlipNet API to access external resources 228 Java Bluetooth development kits for 105 JAD Java Application Descriptor file 144 Java for creating enterprise Bluetooth applications 226 integrating Bluetooth with 33 43 and OBEX 115 136 when not to use Bluetooth with 33 34 Java 2 Micro Edition J2ME 42 75 96 186 Java Bluetooth APIs 45 73 Java Bluetooth development kits for J2SE 105 Java Bluetooth SDK vendors 4243 Java implementation of Micro BlueTarget 186 187 Java OBEX API 115 136 Java Real Time Technology 34 Java Specification Request 35 Java io package 80 Java util stack 19 Javax bluetooth package 36 37 259 264 DataElement 59 60 65 260 DeviceClass 53 57 58 261 DiscoveryAgent 52 56 57 63 64 261 DiscoveryListener 57 64 261 262 L2CAPConnection 71 72 262 LocalDevice 51 53 56 262 ServiceRecord 58 59 64 263 UUID 61 63 264 Javax microedition io package 80 122 Javax microedition io Connection class 122 Javax microedition rms RecordListener 80 Javax microedition rms RecordStore 80 Javax obex package 36 116 121 122 265 268 classes in 38 ClientSession class 122 Header Set interface 117 122 123 Operation class 122 123 ResponseCodes class 120 123 126 ServerRequestHandler class 1
94. Jini enabled printer can provide a printer service in a Jini federation but there s nothing stopping it from providing a random number generator service to the federation as well a Service Consumers are clearly the entities that have an interest in using the services that are available in the Jini federation Lookup Services LUS are the Jini services that act on behalf of Service Providers to host their services This is also the directory that Service Consumers use in order to find services in the federation Before the federation is formed these entities must exist see Figure 12 1 lockup Service h N Service Comsumer Service Provider Servicelten Figure 12 1 These three entities must exist before a Jini federation is established The federation itself hasn t been formed because the entities don t know anything about each other yet Discovering a Lookup Service In order to get the ball rolling the clients Service Providers or Service Consumers must discover a Lookup Service Note A Jini federation can have more than one Lookup Service Jini defines three discovery mechanisms Multicast announcement from a Lookup Service Multicast request from a client Unicast request from a client A Lookup Service can use multicast announcements periodically to advertise its presence on the network Interested clients Service Providers or Service Consumers in particular can use the information provided in an announcem
95. L null System out printin No service available ng else if connectionURL startsWith btspp StreamConnection connection getconnection op connection openOutputStream ip connection openInputStream WriteThread wrthr new WriteThread op wrthr start readData private void readData throws IOException f char data int i 0 do data char ip read System out print data if data 0x0d System out printin while true wWhen a device is discovered it is added to the remote device tabl public synchronized void deviceDiscovered RemoteDevice btDevice DeviceClass cod System out printin New Device discovered btDevice getBluetoothAddress device count btDevice When a service is discovered in a particular device and the connection url is not null then the thread that is waiting in the main is notified public synchronized void servicesDiscovered int transID ServiceRecord servRecords records new ServiceRecord servRecords length records servRecords for int i 0 i lt servRecords length i int atrids servRecords i getAttributeIDs String servName String DataElement servRecords i getAttributeValue 0x100 getValue System out printlin Service Name servName connectionURL servRecords 1i getConnectionURL ServiceRecord NOAUTHENTICATE_NOENCRYPT true System out printin Con
96. P based Note Jini also supports members in a federation with non TCP IP based connections through surrogates The functionality of members in a Jini federation can be summarized in six mechanisms Lookup Discovery Join Leasing Transactions m Events Lookup Lookup is a Jini service that acts much like a directory For instance if a printer wants to provide printer services to a Jini federation then it must register that service with a Lookup Service Conversely if you are participating in a Jini federation and you want to print you must check the Lookup Service to see if any printer services are available Note As you can see finding services in Jini has a centralized approach by going through a Lookup Service Bluetooth has a decentralized approach to finding services since you need to perform a search on each device in your piconet to find what services are available Discovery The process of finding a suitable Lookup Service in a Jini federation is referred to as discovery Note The concept of discovery in Jini is radically different compared to that in Bluetooth In Jini discovery is simply finding a Lookup Service In Bluetooth discovery allows you to find Bluetooth devices as well as the services that they offer Join Once a Lookup Service has been found a service may join that Lookup Service by providing one or more Java objects The Join protocol defines the mechanism to accomplish this Leasing The
97. PrintServiceLookup class 101 PrintStatus class 102 Profile interdependencies 28 30 Profiles Bluetooth 23 28 vs J2ME profiles 29 30 OBEX to implement 116 TCP IP based 252 UUID values for 62 Profiles J2ME 75 Profiles JSR 82 compliant required 39 PROJECT HEX file 187 Protocol Analyzer Mobiwave BPA D10 163 173 1 78 data captured by 174 175 data transmission sniffing 173 Protocol layers Bluetooth UUID values for 61 Protocol multiplexing 20 Protocol stack Bluetooth 17 23 Protocol stack Bluetooth layers 18 20 23 Protocol DescriptorList 130 Protocols Bluetooth Palm DK supported 269 Proximity measurement 34 PsiNode development platform 254 255 PUT operation OBEX 121 123 135 136 Index R Radio frequencies 13 Radio signals 12 34 Radio spectrum 12 17 Radios Bluetooth 13 See also Bluetooth devices RecordListener object 80 RecordStore object 80 Remote Device class javax bluetooth 53 57 263 authorize method 158 encrypt method 162 isAuthenticated method 157 isEncrypted method 162 isTrustedDevice method 158 Request packet OBEX 121 Response codes OBEX server 123 126 Response packet OBEX 121 ResponseCodes class javax obex 123 126 267 Restaurant lobby arcade 9 Retail store Bluetooth device tracker for 233 240 RetrieveDevices method 56 57 RFCOMM wireless serial port 21 connections 67 70 vs L2CAP 72 RFCOMM layer 25 RI Refere
98. REMOTE static java lang String PERIPHERAL SENSING DEV static java lang String PERIPHERAL SHORT static java lang String PHONE static java lang String PHONE CELLULAR static java lang String PHONE CORDLESS static java lang String PHONE ISDN static java lang String PHONE SHOR static java lang String PHONE SIMCARD static java lang String PHONE SMART PHONE static java lang String PHONE WIRED static java lang String UNKNOWN static java lang String UNKNOWN SHORT Constructors ClassOfDevice boolean limitedDisc boolean positioning boolean networking boolean rendering boolean capturing boolean objectTransfer boolean audio boolean telephony boolean information java lang String majorClass java lang String minorClass Constructs a ClassOfDevice object ClassOfDevice byte classOfDevice Constructs a ClassOfDevice object from a bytel ClassOfDevice java lang String classOfDevice Constructs a ClassOfDevice object from a string Methods boolean equals java lang Object obj Compares this ClassOfDevice with an Object and returns true if they are equal byte getBytes Returns the byte representation of this ClassOfDevice object int getIconId Returns the Icon Id for the Class of Device java lang String getMajorTypeText Returns the Class of Device Major type as a Long text description java lang String getMajorTypeText boolean longText Returns the Cla
99. Tech had the pleasure to study under Mr Miller Mr Raymond and Mrs Ashford Dr Steve Kahn was alittle disappointed that didn t finish my degree with the Mathematics Department after joined the Emerging Scholars Program but he deserves to be mentioned also want to thank Dr Chaudhary for giving me the opportunity to study and research with him in the Parallel and Distributed Computing Lab at Wayne State Very few students were eligible to work in the undergraduate research program and I m grateful to Bill Hill for allowing me to be a part of it wouldn t be the person that am today without the spiritual guidance of my pastors at Bethlehem Temple Church Many thanks to the late Bishop Jackson the late Bishop Porter Elder Clark and the whole church family I m the youngest of seven children so each one of my siblings played a role in shaping my life and career Thanks to Theresa Valerie Darlene Barbara Mark and Tyrone definitely have to give special thanks to Mom and Dad because they ve dealt with me for 26 years of my life They did an excellent job raising all seven children with college educations Thanks to Thaddeus Johnson for being a good friend In order to stay smart you have to hang around smart people Finally want to thank my wonderfully sweet wife Schrell She was very patient and understanding while wrote this book She is truly a virtuous woman Bruce Hopkins Numerous people have provided assist
100. VICE SEARCH C f respCode SERVICE SEARCH TERMINATED OMPLETED n System out println n SERVICE SEARCH f respCode ERVICE SEARCH NO RECORDS services 0 None synchronized this this notify System out println n SERVICE_SEARCH_N _TERMINATED n O_RECORDS n if respCode SERVICE_SEARCH_DEVICE_NOT_R System out println n SERVICE_SEARCH_D public void inquiryCompleted int discType this notify EACHABLE EVICE_NOT_REACHABLE n In order to port these examples to another JSR 82 SDK just remove the import statement import com atinav bcc and BCC BCC BCC BCC the stack initialization code setPortName COM1 setBaudRate 57600 setConnectable false setDiscoverable DiscoveryAgent NOT_DISCOV ERABLE Your code is now 100 percent JSR 82 compatible The next step is to follow the instructions of your JSR 82 implementation on how to initialize your stack In some cases as with the Rococo implementation no additional code is needed at all Summary This chapter gave you your first fully working example of a wireless application using Java and Bluetooth We gave you two examples and together they demonstrated stack initialization device management device disc
101. X Listing 7 1 FTServer java Listing 7 2 FTClient java Chapter 8 Using a Bluetooth Simulator Listing 8 1 mydevice xml Listing 8 2 ChatServer java Listing 8 3 ChatClient java Chapter 9 Bluetooth Security Listing 9 1 Bank Account Information Listing 9 2 A 1024 Bit Encryption Key Listing 9 3 Bank Account Information Encrypted with the CAST Algorithm Listing 9 4 ServerApp java Listing 9 5 ClientApp java Chapter 10 Wireless Embedded Systems with the Micro Blue Target Listing 10 1 L2CAPEchoServer java Listing 10 2 L2CAPEchoClient java Listing 10 3 SPP2COMM java Chapter 11 Enterprise Bluetooth Applications with the Ericsson BlipNet Listing 11 1 Tracking java List of Sidebars Chapter 2 Bluetooth 1 1 Bluetooth Profiles vs J2ME Profiles Chapter 5 Bluetooth with J2ME MIDP Working with the Example Code Chapter 6 Creating a Bluetooth Print Server with JPS API Printers and Print Services Chapter 7 Java and OBEX More on Connection URLs and the SDDB Chapter 8 Using a Bluetooth Simulator Difference Between a Simulator and an Emulator Chapter 9 Bluetooth Security More on Mobiwave BPA D10
102. X without Bluetooth Bluetooth is simply one of many transports with which OBEX can operate The classes and interfaces that comprise the Java Bluetooth specification are briefly described in Tables 3 1 and 3 2 These classes and their methods are covered as needed in the following chapters and their APls are listed in detail in Appendix A and Appendix B Table 3 1 Classes in the javax bluetooth Package CLASS NAME DESCRIPTION DiscoveryListener TheDiscoveryListener interface allows an application to receive device discovery and service discovery events L2CAPConnection TheL2CAPConnection interface represents a connection oriented L2CAP channel L2CAPConnectionNotifier TheL2CAPConnectionNotifier interface provides an L2CAP connection notifier ServiceRecord TheServiceRecord interface describes characteristics of a Bluetooth service DataElement TheDataElement class defines the various data types that a Bluetooth service attribute value may have DeviceClass TheDeviceClass Class represents the class of device CoD record as defined by the Bluetooth specification DiscoveryAgent TheDiscoveryAgent class provides methods to perform device and service discovery LocalDevice TheLocalDevice Class represents the local Bluetooth device RemoteDevice TheRemot eDevice class represents a remote Bluetooth device UUID Thevurp class defines universally unique identifiers Bluetoot
103. a Bluetooth enabled printer for printing Hard Copy Cable Replacement Profile The Hard Copy Cable Replacement Profile is what we call the Advanced Printing Profile With this profile you can print any printable document to a Bluetooth enabled printer If you don t already have the driver for that printer that s okay the printer will give it to you Basic Imaging Profile The Basic Imaging Profile is intended to be used by imaging devices like cameras for remote control image transfers and downloading Hands Free Profile The Bluetooth enabled hands free kits in automobiles use the Hands Free Profile to allow the driver to place and receive calls from a Bluetooth enabled phone Human Interface Device Profile As you might have guessed the Human Interface Device Profile has a requirement that the HID Protocol must exist in the underlying Bluetooth stack This profile defines the case scenarios for using Bluetooth enabled human interface devices like keyboards and mice One of the goals of this profile is that a Bluetooth enabled device that conforms to the HID Profile should run for three months on three AAA alkaline batteries Profile Interdependencies The profiles are heavily dependent upon each other and you should already know that every profile depends upon the Generic Access Profile The Bluetooth profiles were designed to be building blocks where a higher level profile is dependent upon the functionality of the lower profi
104. a subclass of the Connection interface and you use it in the same manner The followin methods are found in L2CAPConnect ion that are not found in Connection m public int getReceiveMTU This method gets the negotiated ReceiveMT U value from the connection m public int getTransmitMTU This method gets the negotiated TransmitMTU value from the connection m public boolean ready This method will return true if there is any data ready to be read If this method returns true then a call to receive will not block the main thread m public int receive byte inBuf Regardless of the ReceiveMTU between your device and the remote device you can set the size of inBuf to be whatever you want it to be If the size of inBuf is great than or equal to the ReceiveMTU then you won t lose any data during a transmission If the size of inBuf is smaller than the size of ReceiveMTU then inBuf willbe filled with data for the incoming packet but the remainder of the data will be lost m public void send byte data Use this method to send data to a remote Bluetooth device via the L2CAP protocol You re free to send any size packet that you want but if you exceed the TransmitMTU size then the excess data will be discarded L2CAP vs RFCOMM So now that you know how to send data between Bluetooth clients and servers using both L2CAP and RFCOM we bet you re wondering about typical usage scenarios for these connections In other words wh
105. able mode stealth mode 81 83 Index O OBEX Object Exchange 21 115 136 called IrOBEX in IrDA protocol stack 116 what it is 115121 OBEX API file transfer example 127 136 OBEX APIs in JSR 82 121 127 OBEX clients and servers message flow between 120 OBEX definition explained 11 7 OBEX headers 117 creating 119 in java obex HeaderSet interface 118 OBEX libraries 116 OBEX Object Model 117 119 OBEX operations 119 134 136 OBEX protocol client server architecture 117 OBEX protocol to implement Bluetooth profiles 116 117 OBEX server response codes 123 126 OBEX server responses 120 123 1 26 OBEX Session Protocol 117 11 9 1 21 Object Model OBEX 117 119 Object Push Profile 27 229 230 232 233 Offices Bluetooth in 6 226 Omnidirectional transmissions 1 OnConnect method 128 OnGet method 128 Opening connections on Bluetooth Server listing 68 69 Operation interface javax obex 123 266 Operation object javax obex 122 126 Operations OBEX 119 134 136 OutputStream 193 Index P Packet data handling with L2CAP 72 Palm DK lmpronto Developer Kit 1 0 for PalmOS 269 included software 271 installation 272 sample application 272 supported Bluetooth protocols 269 system requirements 270 Palm SD Bluetooth card for PalmOS 4 devices 15 PalmOS 4 devices Palm SD Bluetooth card for 15 PalmOS 4 1 Fossil Wrist PDA with 9 PalmOS emulator 140 27 1 PalmOS platform
106. age capability Figure 9 1 shows a picture of the device Figure 9 1 The Mobiwave BPA D10 Bluetooth Protocol Analyzer Listing 9 4 presents the server code for our security example Listing 9 4 ServerApp java import import import public java ld javax bluetooth com atinav standardedition io class ServerApp public static void main String args ServerApp a new ServerApp null L2CAPConnection con InputStream in nu OutputStream out String serviceURL LocalDevice local dais nul nu L2CAPConnectionNotifier service null Ty btl2cap localhost 1111 name ATINAV authorize true authenticate true encrypt false jis try local LocalDevice getLocalDevice System out println n Atinav aveLink Bluetooth Server Application n System out printin n System out printin My BDAddress local getBluetoothAddress System out printin n service L2CAPConnectionNotifier Connector open serviceURL Add the service record to the SDDB and accept a client Connection con service acceptAndOpen System out println nConnection established to the remote device n byte data new byte 1000 while con ready try Thread sleep 1 catch InterruptedException ie con receive data System out printin Data received at the Server Side new String data String strDa
107. ample of a Java Bluetooth application is explained in Chapter 5 Before we present the code however we provide a short review of the J2ME MIDP Chapter 6 Creating a Bluetooth Print Server with JPS API Now with acomplete example under your belt things will start to get pretty exciting In Chapter 6 we introduce you to the Java Printing API and show you how to create a Bluetooth print server Chapter 7 Java and OBEX Chapter 7 covers the foundation of the OBEX protocol and provides an example on how to transfer files using the javax obex package of the JSR 82 Chapter 8 Using a Bluetooth Simulator As you might have guessed this chapter is all about how to create Java applications that interact with virtual Bluetooth devices In this chapter the entire Bluetooth network is simulated in software Chapter 9 Bluetooth Security Chapter 9 covers the security measures provided by the Bluetooth specification in order to make wireless applications more secure Chapter 10 Wireless Embedded Systems with the Micro BlueTarget The primary focus of Chapter 10 is the Micro BlueTarget by Smart Network Devices In this chapter we explore the possibilities of creating applications with a fully functional computer that fits in your hand and includes an implementation of the JSR 82 Chapter 11 Enterprise Bluetooth Applications with the Ericsson BlipNet In Chapter 11 we introduce you to enterprise Bluetooth applications and show you how to construct the
108. ance advice and encouragement during the preparation of this book Major contributors of material ideas insights solutions and explanations that have found their way into this book include James Jose Salman Ali Rajesh Rabindranath Sudhin Latheef Vaishali Patil and Sajith M Nair Besides them my teammates at Atinav especially George Mathew Cipson Jose and Dinkar Raj have contributed suggestions fixed program bugs and made imperceptible contributions too numerous to mention am also grateful to Mr Lim Siong Huat and his colleagues at Mobiwave for extending their support by providing timely advice and necessary equipment Without him the chapter on Bluetooth security would not have materialized Ranjith Antony Introduction In the near future Bluetooth wireless technology will be embedded into nearly every consumer electronics device Devices like mobile phones PDAs laptops desktops calculators watches keyboards mice printers scanners cameras and video game consoles are just a sample of what device manufacturers will be embedding with Bluetooth Today Bluetooth chipsets can be purchased in mass quantities for 5 so it s only a matter of time before many of your personal devices become Bluetooth enabled With Java you get the ability to create applications that are agnostic of their underlying hardware platform As you can see this makes Java the perfect programming language for Bluetooth Regardless of the hard
109. ansactionID i 1 record null deviceList new Vector Adds the transaction table with the transaction ID provided private void addToTransactionTable int trans for int i 0 i lt transactionID length i if transactionID i 1 transactionID i trans return Removes the transaction from the transaction ID table private void removeFromTransactionTable int trans for int i 0 i lt transactionID length i if transactionID i trans transactionID i 1 return Completes a service search on each remote device in the list until all devices are searched or until a cable replacement peer is found that this application can connect to private boolean searchServices RemoteDevice devList UUID searchList new UUID 2 Add the UUID for L2CAP to make sure that the service record found will support L2CAP This value Bluetooth Assigned Numbers document searchList 0 new UUID 0x0100 Add the UUID for the cable replacement servic to use to the list of UUIDs to search for This is a fictional cabl searchList 1 new UUID is defined replacement service UUID FFE EDDCCBBAA998877665544332211 in the that we are going false Start a search on as many devices as the system can support for int i 0 i lt devList length i System out pr
110. anvas protected void pauseApp public void destroyApp boolean unconditional public void exitStealth destroyApp true notifyDestroyed public void exitTimer tm cancel tsk cancel class GUI extends Canvas implements CommandListener private Command exitCommand private Image img null private Image imgArc null private Stealth midlet public int i 0 used for creating the beam public int count 0 used to create the blinking public boolean cancel false int x 30 int y 30 int wd 5 int ht 10 public GUI Stealth midlet this midlet midlet exitCommand new Command Exit Command EXIT 1 addCommand exitCommand setCommandListener this try img Image createImage phone png catch java io IOException e System err printin Unnable to locate or read image png try BCC setPortName COM1 BCC setBaudRate 57600 BCC setConnectable false LocalDevice localDevice LocalDevice getLocalDevice discoveryAgent localDevice getDiscoveryAgent device new RemoteDevice 10 discoveryAgent startInquiry DiscoveryAgent GIAC this catch BluetoothStateException btstateex btstateex printStackTrace public void deviceDiscovered RemoteDevice btDevice DeviceClass cod The method is fired every time a device is discovered The inquiry is cancelled after the fi
111. applications for both the J2ME and J platforms Note that J2SE Bluetooth applications will not be JSR 82 compliant until the GGF for J2SE released Product Features The following features are supported by the Rococo Im pronto Simulator Provides full support for L2CAP RFCOMM OBEX SDP and HCI protocols Provides a management console for tracking and controlling the runtime behavior of simulated devices Runs JSR 82 code on simulated Bluetooth devices a Has full logging capability for Bluetooth events and can capture events for specific devices with event filteri Installation Guide The Impronto Simulator runs on any J2SE environment including Windows and Linux You can obtain a free tri the software from the Rococo Web site http www rococosoft com In order to install the software on Windows 2000 just execute simulator exe When installing the software on UNIX platforms you need to execui simulator bin The Simulator requires at least 64 MB of RAM and 5 MB of free disk space Figure 8 1 is a scree of the installation program Choose Product Features Full installation i Custom nana Cance _ Prenou Figure 8 1 The Rococo Impronto Simulator version 1 1 installation screen In order to verify that your installation went smoothly you should try to build the example applications that are included with the Impronto Simulator Echo Chat and AirHockey First you should open a command prome run the setEnvVars script On Windo
112. area DiscoveryAgent gives you two methods to work with startInquiry and retrieveDevices public boolean startInquiry int accessCode DiscoveryListener listener After you have instantiated your DiscoveryAgent you use this method to make your Bluetooth device searct for other devices in the area The length of the inquiry is totally dependent upon the implementation of the Java Bluetooth specification The accessCode canbe one of the following DiscoveryAgent constants NOT_DISCOVERABLE LIAC or GIAC You must also pass a reference to a class that implements the DiscoveryListener interface When new devices are discovered event callbacks are passed back to this object This method will return t rueif the device successfully went into discovery mode The startInquiry method is the only way to perform device discovery without blocking the current thread public RemoteDevice retrieveDevices int option Use the retrieveDevices method to geta list of RemoteDevice objects that were found by previous inquiries The opt ion field has either the value of 0 for CACHEDor1 for PREKNOWN For your convenience CACHED and PREKNOWN are also defined as constants in the DiscoveryAgent class Unlike the start Inquiry method this method blocks the calling thread until it returns CACHED and PREKNOWN devices are determined by the BCC Note For the most part a CACHED device is simply a Blue tooth device that was found
113. as a Jini Lookup Service host and is a perfect solution for creating a low cost small footprint remote 1 Wire sensor controller A picture of the PsiNode is shown in Fiqure 12 10 gt Figure 12 10 The PsiNode development platform The Ericsson Bluetooth module is covered by two metal plates and is connected to the Dallas Semiconductor TINI microcontroller Note Any ordinary TINI device i e a non Bluetooth enabled TINI can function as a Jini Lookup Service in a Jini federation PsiNaptic also makes software for this purpose called JMatos and you can get it from their Web site http www psinaptic com The Benefits of Bluetooth and Jini So what are the advantages of integrating Bluetooth and Jini into devices In the case of mobile devices an all Bluetooth Jini federation allows devices to form smarter networks A Jini federation allows Bluetooth devices to interoperate with more flexibility without being constrained by the limits of Bluetooth profiles More importantly a Jini federation brings to the table the concepts of events transactions and leasing which allows for more fault tolerant and robust Bluetooth applications In a hybrid Bluetooth Jini federation Bluetooth devices that are not capable of joining the federation and using its services can interact with the bridge device and consume the services of the federation Conversely the bridge device can provide wireless services to the Jini federation by interac
114. asynchronous computing architectures in order to achieve the best optimum system performance The Bluetooth Implementation On the Bluetooth side of things the CSR baseband controller handles all low level Bluetooth protocols up to the HCI interface The corresponding firmware is located in a separate flash memory refer back to Figure 10 5 which can be updated dynamically through the HyNetOS host system An HCI driver L2CAP RFCOMM SDP and some of the basic profiles like General Access Profile Serial Port Profile LAN Access Profile and Service Discovery Application Profile comprise the Bluetooth portion of the HyNetOS protocol manager Now that you have a general overview of the underlying hardware implementation of the Micro BlueTarget let s take a look at the OS and included software for this device Application Development on the Micro BlueTarget Platform The core HyNetOS system is contained in a single file named PROJECT HEX Figure 10 7 is a diagram of the r map of the Micro BlueTarget s 2MB flash memory module Bootloader Code 64kB HyNet OS and Configuration Files Up to 300kB Java Core Libraries Up to 200k8 Free Disk Space for User Files and Applications Approx 1550kB Figure 10 7 The memory map of the Micro BlueT arget End user applications have about 1 5MB of space flash disk Apart from the bootloader section also called the ROM section the remaining flash memory space is organiz
115. ate on try bt_out bluetoothport openOutputStream catch Exception e System out printin Bluetooth output stream open exception e System out printin send serial data on Bluetooth link try bt_out write rxdata bt_out flush catch Exception e System out printin Bluetooth output stream write exception e else System out printin No Bluetooth link try to establish one Find a cable replacement service in the local area ServiceRecord cableReplacementService client findCableReplacementService if cableReplacementService null retrieve the connection URL string String conURL cableReplacementService getConnectionuURL ServiceRecord NOAUTHENTICATE_NOENCRYPT false try Create a connection to the SPP peer bluetoothport StreamConnection Connector open conURL catch Exception e System out printin Failed to establish Bluetooth link e if bluetoothport null try open an OutputStream on the Bluetooth connection bt_out bluetoothport openOutputStream catch Exception e System out printin Bluetooth output stream open exception e and send the data from the serial port System out printin send serial data on Bluetooth link try bt_out write rxdata bt_out flush catch Exception e S
116. ation methods void abort HeaderSet getReceivedHeaders int getResponseCode int getResponseCode Class Password Authentication constructor PasswordAuthentication byte userName byte password methods byte getPassword byte getUserName Class ResponseCodes fields static int OBEX DATABASE FULL static int OBEX DATABASE LOCKED static int OBEX HTTP _ ACCEPTED static int OBEX HTIP BAD GATEWAY static int OBEX HTTP BAD METHOD static int OBEX HTTP BAD REQUEST static int OBEX HTTP _CONFLIC static int OBEX HTTP CREATED static int OBEX HTTP ENTITY TOO LARGE static int OBEX HTIP FORBIDDEN static int OBEX HTIP GATEWAY TIMEOUT static int OBEX HTTP GONE static int OBEX HTIP INTERNAL ERROR static int OBEX HTTP LENGTH REQUIRED static int OBEX HTTP _MOVED PER static int OBEX H P_MOVED EMP static int OBEX_HTTP_MULT_CHOICE static int OBEX_H P_NO_CONTENT static int OBEX_HTTP_NOT_ACCEPTABLE static int OBEX_HTTP_NOT_AUTHORITATIVE static int OBEX_HTTP_NOT_FOUND static int OBEX_HTTP_NOT_IMPLEMENTED static int OBEX_H P_NOT_MODIFIED static int OBEX_HTTP_OK static int OBEX_HTTP_PARTIAL
117. ation java lang String uri java lang String id java lang String contents Constructs a WapServiceIndication WapServiceIndication java lang String uri java lang String id java lang String expires byte action java lang String contents Constructs a WapServiceIndication WapServiceIndication java lang String uri java lang String id java lang String expires java lang String contents Constructs a WapServiceIndication Methods boolean equals java lang Object obj Compares this WapServiceIndication with an Object and returns true if they are equal byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String getObexType Returns the mime type of this ObexPushObject int hashCode Returns a hashCode for this WapServiceIndication java lang String toString Returns a String representation of this WapServiceIndication Class WapServiceLoading public final class WapServiceLoading extends java lang Object implements ObexPushObject java io Serializable ThewWapServiceLoading class models the WAP Service Loading This service provides the ability to cause a user agent ona terminal to load and execute a service that for example can be inthe form of a WML deck The Service Loading contains an URI indicating the service to be loaded by the user agent without user intervention when appropriate Objects of the
118. ation with the client ReadThread rdthr new ReadThread ip rdthr start writeData private void writeData throws IOException int data 0 do try data System in read op write data catch IOException e while true class ReadThread extends Thread InputStream ip null public ReadThread InputStream inp ip inp public void run char data int i 0 do try Read data from the stream data char ip read System out print data This is a bit sneaky and hard to explain comment out the following line to s the difference in how the application behaves if data 0x0d System out println catch IOException e while true public class ChatServer public static void main String args throws IOException System setProperty improntolocaldevice friendlyname ChatServer Server chatServer new Server Listing 8 3 ChatClient java import java io import javax bluetooth import com rococosoft 1io class Client implements DiscoveryListener private static LocalDevice localDevice null private DiscoveryAgent discoveryAgent null private String connectionURL null private RemoteDevice device null private ServiceRecord records null private boolean inquiryCompl false int count 0 int maxSearches 10 InputStream ip
119. ator Okay now that you ve set up your environment let s see what it takes to get your code running within the Impro Simulator environment In order to link your application code to the virtual Bluetooth devices that you ve createc need to specify an improntolocaldevice friendlyname property for your application In the J2SE you c this by executing the following line of code at runtime java Dimprontolocaldevice friendlyname TestPDA RemoteControl That s of course assuming that the name of your application is RemoteCont rol and the friendly name of your device is Test PDA You can also specify this property within your Java class itself before calling any JSR 82 co System setProperty improntolocaldevice friendlyname TestPDA If you re creating a J2ME MIDP application you can set this property in your MIDlet s Java Application Descriptc JAD file For example the JAD file would contain the following line impronto localdevice friendlyname foo You must also insert the following code into your MIDlet s constructor so that Impronto Simulator can read the J file using the getAppProperty method of MIDlet import com rococosoft impronto configuration import javax microedition midlet public class SomeMIDlet extends MIDlet public SomeMIDlet Configuration setConfiguration new MIDPConfigurationImpl this Note Any application that uses pure JSR 82 code i e no vendor libraries can run in the simulato
120. ayers of the Bluetooth stack and their purpose Table 2 3 Layers of the Bluetooth Protocol Stack SHORT FULL NAME DESCRIPTION NAME HCI Host Controller Interface The layer that interfaces the host ie the PC and the controller the Bluetooth module L2CAP Logical Link Control and The layer that handles all data transmissions from Adaptation Protocol upper layers SDP Service Discovery Protocol The layer that discovers services on Bluetooth devices in the area RFCOMM RFCOMM The layer that allows you to create a virtual serial port and to stream data TCS BIN Telephony Control The layer that allows you to create control signals Protocol Specification for audio applications WAP Wireless Access Protocol The adopted protocol that allows you to view content in Wireless Markup Language WML OBEX Object Exchange The adopted protocol that allows you to send and receive objects BNEP Bluetooth Network The layer that encapsulates other protocol data Encapsulation Protocol packets into L2CAP packets HID Human Interface The layer that traffics the controls signals and Device Protocol data for input devices like keyboards and mice Note For an exhaustive list of all the new and upcoming Bluetooth protocols go to the Bluetooth Member site at http www bluetooth org Profiles So let s say that you own a Bluetooth enabled PDA and a Bluetooth enabled wireless phone Both of the devices have Bluetooth stacks H
121. blish the dial up connection Sometimes you need to connect two cables together to accomplish this feat Bluetooth eliminates all the hassle from this scenario by creating a standardized method for wireless dial up networking You can even keep your wireless phone at your hip or in your purse while you surf the Web on your laptop The same applies for PCs or PDAs that want to use your phone to connect to the Internet This is really convenient whenever your broadband connections at home go down for servicing You can simply place your wireless phone in the vicinity of your PC and that s it you re connected Personal Networks PC to PC Bluetooth is great for connecting two PCs together at a moderate speed If you want higher speeds or if you need to transfer large files then you re better off using Wireless LAN technology On the other hand Bluetooth is good at creating small personal networks So this is a great technology if you re having an impromptu meeting with coworkers Bluetooth also has the added capability to discover new devices when they enter your network Cable Replacement PC to Peripherals You can imagine Bluetooth as functioning like any other protocol to connect to your peripherals such as serial RS 232 parallel USB or Firewire In the near future your personal computer will be equipped with a Bluetooth port in the same manner that it currently features a serial and USB port You can use Bluetooth to connect to your p
122. bout how to use Bluetooth and Java you need to know when it is not a good idea to use the two technologies together When NOT to Use Bluetooth and Java You should not use Bluetooth with Java for the following purposes Signal strength indicator Voice applications a Distance measuring The next few sections explain why to avoid those scenarios Signal Strength Indicator Let s say that you have two Bluetooth units and you want to know what the signal strength is between them A good example is when you want to use the services of a network access point A signal strength indicator would let you know if you were within range Well Java is not the ideal language for that sort of application because that kind of information is not exposed to the level where a JVM would have access to it The JVM will let you know if you are within range or not within range there is no middle ground In this scenario you re better off using a native language for your device such as C or C Voice Applications Now you ve already read Chapter 2 and you realize that Bluetooth is a really great technology because you have the ability to transmit voice and data information wirelessly to other Bluetooth devices Suddenly you get ideas bubbling in your head about how great it would be to create a speech to text application on your Bluetooth enabled phone Unfortunately Java especially J2ME is not well suited to this arena just yet Performance is a key fact
123. c void main String args throws IOException FTServer server new FTServer ocalDevice localDevice LocalDevice getLocalDevice SessionNotifier sn SessionNotifier Connector open btgoep localhost 1106 name FTP System out printin Waiting for a client connection sn acceptAndOpen server System out printin A Client now connected More on Connection URLs and the SDDB Theconnect ion URL and the service record attributes in the SDDB are closely related Although software developers may not care about the inner details of the SDDB this information will be helpful when searchin for services on remote devices In the File Transfer Server example the SDDB gets populated with various components of the connection URL Connector open btgoep localhost 1106 name FTP ServiceRecordHandle is a 32 bit unsigned integer that has an attribute ID of 0x0000 This is a unique identifier for each service in the SDDB The value of ServiceRecordHand_le is generated internally and remains unique throughout the database ServiceClassIDList is a data sequence of UUIDs with an attribute ID of 0x0001 The underlying Service Discovery Protocol SDP implementation generates this list with the first element as the UUID give in the Connection URL In this example the first UUID in this list will be 0x1106 ServiceRecordState is a 32 bit unsigned integer that has an attribute ID of 0x0002 The underlying SC imple
124. canvas i lt 3 canvas i canvas itl else canvas i 0 switch canvas i case 1 canvas x 30 canvas y 30 canvas ht 10 break case 2 canvas x canvas x 5 canvas y canvas y 3 canvas ht canvas ht 6 break case 3 canvas x canvas x 5 canvas y canvas y 3 canvas ht canvas ht 6 canvas count canvas count 1 break canvas repaint Piconet Browser Example The Piconet Browser is a handy utility that demonstrates all the concepts presented in the last example and also includes the functionality of service discovery It s really something that you would want to keep with you at all times so after you get this example working be sure to load it on your mobile phone or PDA Using the Piconet Browser you can see what Bluetooth devices are in the vicinity After the list is displayed you can select a particular Bluetooth device to see what services it offers The algorithm for this example is pretty simple First the MIDlet creates a form and displays it with buttons labeled Search and Exit see Figure 5 6 DefaultColorPhone BIBI EG aa File Transfer Printer Figure 5 6 The initial screen for the Piconet Browser application After pressing the Search button the application performs a device discovery and displays the search results see Figure 5 7 Figure 5 7 The Piconet Browser displays a list of Bluetooth devices in the area After you select a Bluetooth device the application will d
125. cation using the Atinav Java Bluetooth SDK Chapter 5 Bluetooth with J2ME MIDP Now that we ve covered a lot of the foundational material let s start creating some Java Bluetooth applications This chapter will give you your first full example of a Java Bluetooth application but before we dive right in we re going to give a brief primer on J2ME and the Mobile Information Device Profile MIDP Afterwards we re going to examine two sample applications Stealth Mode and the Piconet Browser Note If you ve already developed a MIDlet or if you have a working knowledge of J2ME then feel free to skip down to the example code in the sections Stealth Mode Example and Piconet Browser Example J2ME Overview Under the general term of J2ME there are two configurations that correspond to two classes of devices The connected device configuration CDC is a classification for devices that have a network connection but have less processing power than a typical desktop computer Set top boxes appliances smart phones and high end PDAs fit into this category The connected limited device configuration CLDC classifies many mobile devices they are capable of making a network connection but it isn t robust or dedicated CLDC devices typically don t have a lot of processing power and many mobile phones two way pagers and some PDAs fit into this category A J2ME Profile is a software layer that is built on top of a configuration not to be c
126. compliance explained 22 Bluetooth device tracker 233 240 Bluetooth devices 13 15 40 41 authentication of 156 classes of 225 connection capabilities of 15 16 creating in Impronto Simulator 142 of the future 8 9 on the market today 3 7 power classes 16 17 TDK USB 83 84 that beep until found 8 Bluetooth devices in the area browsing 90 Bluetooth discovery modes 52 Bluetooth host 41 Bluetooth Print Server creating with JPS API 97 113 Bluetooth printer adapter 97 Bluetooth profiles 23 28 vs J2 ME profiles 29 30 OBEX to implement 116 TCP IP based 253 UUID values for 62 Bluetooth Protocol Analyzer 163 173 1 78 Bluetooth protocol stack 17 23 Bluetooth protocol stack layers 18 20 23 Bluetooth protocols to send and receive data 115 Bluetooth Qualification Body 31 Bluetooth qualification process 31 32 Bluetooth Qualification Web site 32 Bluetooth radios 13 See also Bluetooth devices Bluetooth security SeeSecurity Bluetooth server authentication 156 157 authorization 158 1 59 connections with Serial Port Profile 68 69 encryption 161 162 Bluetooth Service explained 191 Bluetooth SIG promoter companies 12 Bluetooth network simulator 137 153 Bluetooth Special Interest Group SIG 1112 Bluetooth specifications page 23 Bluetooth stack 41 47 51 Bluetooth stack initialization 47 51 Bluetooth version 1 1 11 32 BluetoothConnectionException class 156 158 162 259
127. computer devices It is also a great cable replacement technology for PCs and laptops It can function as a universal connector between your peripherals and devices and you may never again need a cable some of which can be expensive to connect your devices together In the next chapter we ll dig right in to the Bluetooth protocol If you re new to Bluetooth this will be your first introduction to a lot of new terminology We ll explain to you the components of the Bluetooth stack and the purpose of Bluetooth profiles When you create your wireless applications you ll interact with the stack and profiles to send and receive data Chapter 2 Bluetooth 1 1 Overview The main focus of this chapter is to describe the inner workings of Bluetooth The most current revision of the protocol is version 1 1 Almost every device on the market today is compliant with Bluetooth version 1 1 although you might be able to find some devices that use the 1 0B version of Bluetooth The differences between Bluetooth 1 0B and 1 1 are beyond the scope of this book The differences are minimal and they really don t apply to Java programmers What can you expect for future versions of Bluetooth like 1 2 and 2 0 Whenever the Bluetooth SIG the group of companies that developed the Bluetooth spec plans to release later revisions of the spec you can expect some things like higher speeds more profiles and backward compatibility with 1 1 We wouldn t expect the newe
128. device is just a radio then what do these radios look like Well Figures 2 1 2 2 and 2 3 are just a sample of devices that are Bluetooth radios Some of these items are used in development kits while others are meant to be used by consumers Figure 2 1 The 3COM USB Bluetooth module controller and Bluetooth implementation in a single package This is most likely the smallest radio that you ve ever seen Figure 2 3 The Palm SD Bluetooth card for Palm OS 4 devices Palm OS is a registered trademark of Palm Inc The examples in this book will use a variety of Bluetooth devices from multiple vendors The example in Chapter 8 however uses no Bluetooth devices at all In that example we simulate the entire Bluetooth network in software using the Rococo Impronto Simulator Point to Point and Multipoint One factor that distinguishes various Bluetooth devices is their connection capabilities If a Bluetooth device can only support point to point communication then it can only communicate to a single Bluetooth device at a time Fiqure 2 4 demonstrates point to point communication in Bluetooth 3 TA Figure 2 4 You can only connect to one Bluetooth device at a time if you have hardware that only supports point to point communication Now point to point communication isn t necessarily a bad thing If you have a Bluetooth phone you really only need one connection to your Bluetooth phone Frankly it doesn t make sense to have multi
129. dicates that a BlipNode software upgrade has been initiated T static int BLIPNODE_WAITING_FOR_CONFIGURATION Indicates that a BlipNode has registered with the server but no configuration exists for that Blip Node static java lang String CLASS_NAM static int CONNECTION_EVENT Fl n Event class of Connection related events static java lang String FRIENDLY_NAME static int OBEX_BUSINESS_CARD_EXCHANGE_COMPLETED T Indicates successful completion of a business card exchange static int OBEX_BUSINESS_CARD_EXCHANGE_FAILED Indicates a failed attempt to exchange business cards with a terminal static int OBEX_BUSINESS_CARD_PULL_COMPLETED Indicates successful completion of a business card pull static int OBEX_BUSINESS_CARD_PULL_FAILED Indicates a failed attempt to pull business card from a terminal static int OBEX_EVENT Event class of OBEX related events static int OBEX OBJECT RECEIVED Indicates that an OBEX object has been received and stored by the server static int OBEX PUSH COMPLETED Indicates successful completion of an OBEX push static int OBEX PUSH FAILED Indicates a failed attempt to push an OBEX object to a terminal static int OBEX PUSH PROGRESS Indicates progress in an ongoing OBEX push static int TERMIN
130. discovery related classes in the Java Bluetooth specification implement the Service Discovery Application Profile The Service Discovery Application Profile in turn uses the Service Discovery Protocol SDF layer in your Bluetooth stack to find services on remote Bluetooth devices CROSS SeeChapter 2 for detailed descriptions of profiles and layers in Bluetooth REFERENCE The following classes are provided in the Java Bluetooth specification for service discovery DiscoveryAgent DiscoveryListener ServiceRecord DataElement and UUID You ll also interact indirectly with the SDDB whenever you want to discover services on a remote Bluetooth device The Service Discovery Database The Service Discovery Database SDDB is the central repository for all service records but it s not a database the sense of Oracle 9i Sybase or even MS Access It s simply a collection of service records and no we don t mean a Java Collections object The JSR 82 implementation is free to implement the SDDB in any form so when a ServiceRecord object is stored in the SDDB it doesn t necessarily mean that the JVM serialized the ServiceRecord object and stored it in a data store If a particular JSR 82 implementation does not store service records in the SDDB as Java objects then it must convert them into ServiceRecord objects when a client performs asearch for services and a match is found Figures 4 1 through 4 4 present graphical depictions of the SDDB Ser
131. e Called when a device was found during an inquiry An inquiry searches for devices that are discoverabl The same device may be returned multiple times public void deviceDiscovered RemoteDevice btDevice DeviceClass cod System out printin Found device btDevice getBluetoothAddress deviceList addElement btDevice public void serviceSearchCompleted System out printin Called when servic This method provi public void servicesDiscovered int transID search is completed or he following method is called when a servic as terminated because of an error Legal values include RVICE SEARCH TERMINATED w SERVICE_SEARCH_COMPLETED SE SERVICE_SEARCH_ERROR S RVICE_SEARCH_NO_RECORDS int transID serviceSearchCompleted 2 respCode ERVICE_SEARCH_DEVICE_NOT_REACHABL J int respCode transID Wye Mes Removes the transaction ID from the transaction table removeFromTransactionTable transID serviceSearchCount synchronized this this notifyAll s If this is and cancel if record null the first record found then the remaining searches Found a service Length of array null System out println System out println if servRecord 0
132. e Before you try out any of the examples in this book it is recommended that you first get your JSR 82 implementation on your development environment installed and configured If you don t have your development environment set up then here s a checklist of the things that you need to do Select a JSR 82 implementation that supports your OS You can find an updated listing of JSR 82 implementations at the companion Web site for this book http www javabluetooth com Select the Bluetooth hardware that is supported by your JSR 82 implementation a Install and configure your development environment Tryout the demo programs that are included with your JSR 82 implementation Determine what stack initialization code if any is used in the demo programs The documentation for your JSR 82 implementation really should point out what you need to do in order to initialize your stack But just in case they don t a dead ringer would be a class that you need to import that s not part of the javax bluetooth or javax obex packages see Appendices A and B for an exhaustive list In some cases your stack initialization code will also be setting the baud rate for your Bluetooth device Stealth Mode Example The Stealth Mode example is a simple program that illustrates the concepts of stack initialization device management and device discovery When the program starts it looks for remote Bluetooth devices as shown in Figure 5 3 Fy DetautColo
133. e Being a singleton object you can only have a single instance of this object in your JVM at a time lts constructor is private so you can instantiate it by using the static get LocalDevice method LocalDevice localdevice LocalDevice getLocalDevice public String getBluetoothAddress Bluetooth devices have unique addresses which are quite similar to MAC addresses for network cards on your PC This class allows you to find out what your Bluetooth address is withthe getBluetoothAddress method It returns a 12 character St ring in the form of something like 00FE3467B092 In most cases your Bluetooth radio shows what your address is somewhere externally but it s nice to have a way to access it programmatically public boolean setDiscoverable int mode In order to allow remote Bluetooth devices to find your device you need to set the discovery mode of your Bluetooth device Table 4 1 contains a list of valid modes and descriptions for the Bluetooth discovery modes Table 4 1 Bluetooth Discovery Modes ACCESS MODE FULL NAME DESCRIPTION VALUE NOT_DISCOVERABLE Not Discoverable Don t allow any devices to discover 0 your device GIAC General Unlimited Allow all devices to discover your 10390323 Inquiry Access Code device LIAC Limited Inquiry Access A temporary access mode that will 10390272 Code revert back to a previous state after 1 minute One question that might be on your
134. e By using a dual UART module the 16752 chip in the device one UART is still free for external serial communication Note The Micro BlueT arget Starter Kit connects the available UART to the RS 232 port This allows developers who don t have a lot of hardware experience to quickly utilize the Micro BlueTarget for external serial communication Note As an option the dual UART device can be substituted by one of the many PIC family microcontrollers This will enable the Micro BlueTarget to externally communicate via other protocols such as SPI 12C and GPIO Some PIC chips will even enable the Micro BlueT arget to have a CAN bus interface or perform A D conversion Here s a quick synopsis of the hardware details of the Micro BlueT arget a 120 MHz 32 bit RISC DSP Hyperstone E1 16XS CPU a 3 3 VDC 250 mA 8MB SDRAM memory 2 1MB flash memory 10 100 Mb s Ethernet interface Integrated Class 2 Bluetooth radio 10m nominal radio range Available serial communication port UART with up to 3 Mb s transfer rate Peripheral I O bus connector addresses 8 bit data RD WR chip selects interrupts The Micro BlueTarget Software Configuration The Micro BlueT arget board runs the HyNetOS SND s specialized operating system for the Hyperstone RISC DSP CPU architecture The HyNetOS was created for primarily two reasons The first reason was to have the smallest possible memory footprint in order to match internal memory sizes of future Systems
135. e you can process input but you won t have direct access to it All of these items are handled by the MIDP implementation and are device dependent This abstraction allows the same MIDlet to run on a Blackberry pager as well as on aPalm PDA Thelow level API on the other hand is designed for applications that need precise placement and control of graphic elements as well as access to low level input events The low level API is well suited for gaming or entertainment based applications Using the RMS for Persistent Storage So how do you store persistent data on a micro device If you think about it a mobile phone probably wouldn t have a file system in order to store its data It s really overkill for such a small device that keeps names and phones numbers to have a file system just for data storage Being aware of this the J2ME architects have developed a viable alternative to storing data persistently called the RecordManagement System RMS The javax microedition rms package contains all the functionality that will enable your classes to read write and sort data in the RMS The RMS is a record oriented database stored in the nonvolatile memory of the mobile device Since it is record oriented the RMS is also referred to as a flatfile system where the data is stored in a series of rows in a table much like the data stored in a conventional database Each row will have a unique identifier A logical representation of a record store i
136. e DiscoveryAgent agent The max number of service searches that can occur at private int maxServiceSearches 0 The number of service searches that are presently in private int serviceSearchCount any one time progress Keeps track of the transaction IDs returned from searchServices private int transactionID The service record to a cable replacement servic private ServiceRecord record Keeps track of the devices found during an inquiry private Vector deviceList The constructor creates an SPP2COMM and prepares th for device discovery and service searching public SPP2COMM throws BluetoothStateException Retrieve the local Bluetooth device object socalDevice local LocalDevice getLocalDevice object Retrieve the DiscoveryAgent object that allows us to perform device and service discovery agent local getDiscoveryAgent Retrieve the max number of concurrent service searches that can exist at any one time try maxServiceSearches Integer parseInt LocalDevice getProperty bluetooth sd trans max catch NumberFormatException e System out printin General Application Error System out printin NumberFormatException e getMessage transactionID new int maxServiceSearches Initialize the transaction list for int i 0 i lt maxServiceSearches i tr
137. e PDA and MID Profiles are both a set of Java classes that extend the functionality of the Connected Limited Device Configuration On the otherhand 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 ona Palm OS PDA in C and it can also be implemented on a Bluetooth enabled printer in Assembler it s just a defined set of functionality Personal Area Networks Piconets and Scatternets When two or more Bluetooth enabled devices come within range and establish a connection a personal area network is formed A personal area network can either be a piconet or a scatternet Figure 2 10 shows Bluetooth devices in a piconet Slave Slave Figure 2 10 In a piconet the slaves can only communicate to the master A Bluetooth piconet has a single master and up to seven slaves No matter what kind of Bluetooth devices are involved they can be phones access points PDAs laptops headsets etc the master of the piconet is the one that initiates the connection The device that accepts the connection automatically becomes the slave Master slave roles are not predefined so if a piconet exists between a laptop and a PDA either device could be the master or the slave Note In certain conditions a role switch between the master and slave is allowed These conditions are explained in the Blue
138. e RemoteDevice Pe Service D S Record 3 T en AN Z Ye 5008 Sr a l selectService 0x1124 1 true Attribute ID Attribute Value 0x0000 Datat lement int WID 0x1124 Figure 4 5 The service discovery process for a PDA that wants to use the services of a Bluetooth keyboar Now let s look at the service discovery related classes in detail javax bluetooth U UID Theuurp class is simply a class that uniquely identifies services in the Bluetooth protocol UUID stands for Universal Unique Identifier Let s say that you have a Bluetooth client device that supports L2CAP connections you want to send a message to a Bluetooth server device just perform service discovery with the UUID of 0x0100 which is the UUID for L2CAP If you have a Bluetooth enabled PDA and you want to send your business card vcf to other Bluetooth enabled devices then you ll perform service discovery with a UUID of 0x1105 which is the UUID for the OBEX Object Push Profile Table 4 3 lists a sample of UUIDs for Bluetooth protocol layers and Table 4 4 lists UUIDs for Bluetooth services and their corresponding Bluetooth profile For instance Headset and HeadsetAudioGateway are both distinct services that are a part of the Headset Profile Therefore each service has its own UUID 0x1108 and 0x1112 respectively Some profiles like the FAX Profile only have one service FAX which has a UUID of 0x1111 A more exhaustive list of UUID
139. e issues of infrared 1 Listings 1024 bit encryption key 160 161 bank account information 160 bank account information encrypted 161 BeamTsk java 87 88 BluetoothSetup1 java 47 48 ChatClient java 146 150 ChatServer java 145 146 ClientApp java 165 1 70 DeviceProperties java 48 51 FTClient java 132 134 FTServer java 128 130 JPSBluetoothPrintClient java 109 1 12 JPSBluetoothPrint java 105 109 JPSPrint java 102 1 04 L2CAPEchoClient java 196 207 L2CAPEchoServer java 193 196 mydevice xm1 143 opening connections on Bluetooth Server 68 69 PiconetMIDlet java 91 95 ServerApp java 163 165 service registration process 66 67 SPP2COMM java 208 223 stack initiation code for Atinav SDK 47 Stealth java 84 87 Tracking java 235 240 LocalDevice class 51 53 56 262 Lookup Service discovery Jini 245 247 Lookup Services LUS Jini 243 247 249 LookupPrintServices method 101 Low level API MIDP 79 Low power wireless technology Bluetooth as 2 LUS Lookup Services Jini 245 247 249 Index M MAME Multiple Arcade Machine Emulator project 138 Manufacturing facility Bluetooth in 182 Master and slave concept 1 30 31 Micro Blue Target Smart Network Devices 179 224 application development on 187 224 Bluetooth implementation of 187 communication between devices 192 207 creating a fixed wireless system 207 223 for external serial communication 184 hardware components block diagram 183 hard
140. e our variables StreamConnectionNotifier notifier null StreamConnection con null LocalDevice localdevice null ServiceRecord servicerecord null InputStream input OutputStream output let s create a URL that contains a UUID that has a very low chance of conflicting with anything String url btspp localhost 00112233445566778899AABBCCDD let s open the connection with the URL and cast it into a StreamConnectionNotifier notifier StreamConnectionNotifier Connector open url rs EFF name serialconn block the current thread until a client responds con notifier acceptAndOpen the client has responded so open some streams input con openInputStream output con openOutputStream now that the streams are open send and receive some data For the most part this is 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 are a few items that need to be pointed 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 whichis 001122334455667788 9 9AABBCCDDEEFF This is simply a custom UUID that was made up for this service a string that s 128 bits long could have been used Finally we have name serialconn in the URL String We could have le
141. e widely used with manufacturing facilities to control relays switches motors test chambers assembly lines robotic arms the list goes on and on Now a large manufacturing facility is very likely to have a considerable number of PLCs each doing a particula Now if you want to monitor the status of a particular PLC you typically would have to walk over to the machine you want to inquire about and hook up a portable computer to the PLC s RS 232 interface You would then run program on the computer that would read the data coming from the serial port of the PLC This in itself can become a tedious process especially if you re the guy who has to check the status onthe PLC Sometimes the hardest part of the job is trying to hook up the serial cable We re not kidding here in some ind environments the PLC may be located in a hard to reach area and the communication ports may be even har reach As you can see PLCs make good candidates to be converted into fixed wireless systems As shown in Figure 10 10 with the addition of a Micro BlueTarget a PLC can instantly become a fixed wireless system The Micro Blue Target will read the data from the RS 232 interface and transmit the data wirelessly witt Serial Port Profile All a status technician needs to do is to come within range of the PLC to gather the data Blo lo POA Micro BlueTarget Programmable Figure 10 10 Using the Micro BlueT arget to create a fixed wireless system SPP2
142. eating a Print Job and Printing After that s done the next step is to create the print job and submit the job to a print service Once you have an instance of a PrintService object just call the createPrintJob method and it will return aDocPrintJob object which is a print job In order to print just call the print method on the DocPrintJobobject and provide it with the document that you want to print as well as the print attributes The code snippet that follows shows how to create a print job and submit it DocPrintJob printJob services 0 createPrintJob try printJob print doc attribSet catch PrintException e Listening for Status Updates Optionally you can listen to status updates on your print job after you have submitted it For instance if you haven t received an update from the printer in a while you may also want to get a status update on the printer itself it may be out of paper or something The classes that enable you to do this are javax print event PrintServiceAttributeListener javax print event PrintJobAttributeListener and javax print event PrintJobListener By implementing these interfaces you ll receive callbacks from the JVM upon changes in state of the printer or the print job A Complete JPS Application JPSPrint Listing 6 1 shows the complete source for JPSPrint java summarizing all the material that we ve covered so far It includes an inner class named PrintStatus which implem
143. educe the expense of creating a development environment for each developer Instead of buying Bluetooth hardware for each and every individual which would be used throughout all the phases of the application development life cycle fewer Bluetooth devices can be purchased and used for only the final phase of application development testing Now on the other hand no matter how good a Bluetooth network simulator may claim to be it is no substitute for scenarios that require the presence of real Bluetooth hardware For instance a Bluetooth network simulator isn t capable of telling you what would happen if you ran your file transfer application code using 3Com or TDK Bluetooth modules A Bluetooth network simulator is also incapable of telling you how your application would behave in the presence of other devices that operate in the 2 4 GHz range like WLAN devices or microwave ovens Due to the absence of any Bluetooth hardware Bluetooth network simulators are also a poor choice for testing the performance of your application such as VO throughput Impronto Simulator from Rococo The Rococo Impronto Simulator is a 100 percent Java application that allows you the developer to create JSF compliant Bluetooth applications Using the Impronto Simulator you can create virtual Bluetooth devices using environment and deploy your code to those virtual devices to see how they interact Note Using the Rococo Impronto Simulator you can create Bluetooth
144. eeted with some information about the school However in the teacher s lounge the BlipNodes can be connected to the same network but have only the LAN Access Profile activated so that teachers can get wireless Internet access BlipNet API Overview The BlipNet 1 1 API consists of 6 packages and 40 classes and interfaces that allow you to create enterprise Bluetooth applications Here s a list of the BlipNet packages m com ericsson blipnet api blipnode m com ericsson blipnet api blipserver m com ericsson blipnet api bluetooth m com ericsson blipnet api event m com ericsson blipnet api obex pushobjects m com ericsson blipnet api util Thecom ericsson blipnet api blipnode package contains classes that deal directly with individual BlipNodes like Bl ipNodeHandle Conversely the package com ericsson blipnet api blipserver contains classes that deal with the BlipServer such as BlipServer and BlipServerConnection If you are looking for classes that pertain to Bluetooth specific things like BluetoothAddress and ClassOfDevice then they are found in the package com ericsson blipnet api bluetooth Almost every application will use one or more of the interfaces contained in the com ericsson blipnet api event package This package contains all the interfaces for listeners and events within the BlipNet For instance if you implement the BlipServerEventListener interface then you can receive callbacks from the JVM when B1lipNodeE
145. egistering user Have You created a username password for this application in BlipManager System exit 1l private BlipServerEventFilter getEventFilter String discoverBlipNodeGroup BluetoothAddress terminals List of BlipNodeIds used for tracking is built from input in line parameters entered at start up of Tracking application BluetoothAddress blipNodeAddressList null BlipNode inquiryOnlyBlipNodes null try inquiryOnlyBlipNodes blipServerConnection getBlipNodes discoverBlipNodeGroup Discover Devices false false catch BlipServerConnectionException e System out printin Could not get BlipNode handles for the BlipNode Group discoverBlipNodeGroup n e System exit 1 Are there any BlipNodes in the specified group if inquiryOnlyBlipNodes length gt 1 blipNodeAddressList new BluetoothAddress inguiryOnlyBlipNodes length for int 0 i lt blipNodeAddressList length i blipNodeAddressList i inguiryOnlyBlipNodes il getBlipNodeID else System out printin Have You inserted at least 2 BlipNodes in the group discoverBlipNodeGroup usage System out printin BlipNodes used for tracking from group discoverBlipNodeGroup for int i 0 i lt blipNodeAddressList length i System out printlin blipNodeAddressList i toStr
146. ent to communicate with the Lookup Service Clients use multicast requests to discover a Lookup Service A Lookup Service receiving a request responds directly to that client Once the address of a Lookup Service is known a client sends a unicast request directly to the Lookup Service The Lifecycle of a Service Provider Now let s assume that a Lookup Service is making periodic multicast announcements A Service Provider hears an announcement and receives from the Lookup Service its serviceRegistrar A ServiceRegistrar is a Java object that is simply the public interface to the Lookup Service It allows a client to register services look up services and request notification of changes in the Lookup Service This interaction is shown in Figure 12 2 Lookup Service NS N h Service Consumer Service Provider Servicelten ServiceRegistrar i j AEN en Figure 12 2 The Service Provider discovers the Lookup Service and receives its ServiceRegistrar object The ServiceRegistrar is used to interact with the Lookup Service via its public methods In the final step of the discovery process the Service Provider receives the serviceRegistrar object which it can use to register its ServiceItem with the Lookup Service Leasing a Serviceltem and Joining a Federation When a Service Provider registers its ServiceItem as shown in Figure 12 3 it also specifies a lease duration for the service If the registration is successful the Look
147. entication process fails A practical example for the usage of Bluetooth authentication would be a Bluetooth enabled hotel business cer hotel that s oriented to business travelers could enable authentication on all of its Bluetooth enabled devices lil printers and scanners in the business center Upon check in a registered guest of the hotel will be given the P in order to access the services in the business center and this would prevent non hotel customers from simply up and using the services that are reserved for hotel guests Server Authentication Bluetooth servers can request authentication by adding the authenticate parameter to the connection URL String The code that follows shows a server using the Serial Port Profile and requesting authentication String url btspp localhost 00112233445566778899AABBCCDDEEFF authenticate tri If the authenticate parameter is set to true then the JSR 82 implementation attempts to enforce authentic when devices connect to the server Note The key word here is attempt ABluetoothConnectionException willbe thrown if the server does not support authentication c there is a conflict with the settings of the BCC It is ultimately the decision of the BCC to allow authent or to throw the exception If the server device has a user interface then the device may prompt the us change the device s settings If the authenticate parameter is set to false then the implementation does not attem
148. ents the PrintJobListener interface This code will provide the status of a print job by displaying a few text messages at the command line Listing 6 1 JPSPrint java import java io import javax print import javax print event import javax print attribute import javax print attribute standard class PrintStatus implements PrintJobListener public void printDataTransferCompleted PrintJobEvent pje System out printin Data delivered to printer successfully public void printJobCanceled PrintJobEvent pje System out printin The print job has been cancelled public void printJobCompleted PrintJobEvent pje System out printin The print job completed successfully public void printJobFailed PrintJobEvent pje System out printin The document failed to print public void printJobNoMoreEvents PrintJobEvent pje System out printin No more events to deliver public void printJobRequiresAttention PrintJobEvent pje System out println Something terrible happened which requires attention public class JPSPrint public static void main String args throws FileNotFoundExceptionf PrintStatus status new PrintStatus Create the DocFlavor for GIF DocFlavor flavor DocFlavor INPUT_STREAM GIF Create an attribute set comprising of the print instructions PrintR
149. equestAttributeSet attribSet new HashPrintRequestAttributeSet attribSet add new Copies 1 attribSet add MediaSizeName ISO_A4 Locate print services which can print a GIF in the manner specified PrintService pservices PrintServiceLookup lookupPrintServices flavor attribSet if pservices length gt 0 DocPrintJob job pservices 0 createPrintJob Adding a PrintStatus Listener job addPrintJobListener status Create a Doc implementation to pass the print data FileInputStream fInput new FileInputStream nicePic gif Doc doc new SimpleDoc fInput flavor null Print the doc as specified try job print doc attribSet catch PrintException e System err println e else System err println No suitable printers Caution The JPS API is apart of JDK 1 4 and older versions of the JDK are not capable of running the JPSPrint example Integrating JPS and Bluetooth Now that you have a full working example of a JPS application under your belt let s see what it will take in orde to turn this ordinary JPS print service into a Bluetooth enabled wireless print server refer back to Figure 6 2 The algorithm for the application is pretty simple The com puter that functions as the print server will start an L2CAP server and wait for clients to connect After an incoming file is received by the server it is printed to a printer using the JPS API Note As
150. er with 256MB of RAM can manage 200 BlipNodes BlipNodes In an enterprise Bluetooth application the BlipServer cannot directly communicate to your Bluetooth enabled clients it has to interface with the BlipNodes Each BlipNode is capable of multipoint communication and includes the following profiles to interact with clients m Generic Access Profile Service Discovery Application Profile a LAN Access Profile Object Push Profile Note The BlipNodes also conform to the WAP over Bluetooth interoperability requirements as defined in the Bluetooth specification Your enterprise Bluetooth application will listen for events from the BlipNodes and act accordingly For instance let s say that you want to track where employees are in the building assuming of course that they are wearing Bluetooth enabled ID badges When users come within range of a BlipNode your application will listen to device discovered events via the Generic Access Profile The BlipNet system is sophisticated enough to let you know which BlipNode detected a user so all you need to dois store that data in a database and create another application to view the results Now let s say that you re the manager of a hotel and you want to allow your customers with Bluetooth enabled devices to send e mails wirelessly from within the conference rooms At these e mail stations the BlipNodes will use the Object Push Profile to send clients the custom e mail application of
151. erAccessException public class BlipServerAccessException extends BlipServerException Thrown by a BlipServerConnection when an application tries to access the server with invalid username or password The reason for denying access can be wrong username password or access from a host other than the host associated with this account Package com ericsson blipnet api blipserver Constructors BlipServerAccessException java lang String s BlipServerAccessException java lang String s java lang Throwable e Interface BlipServerConnection public interface BlipServerConnection ABlipServerConnection is used to attach BlipNode event listeners to the server and to get handles for connected BlipNodes Package com ericsson blipnet api blipserver Methods void addEventListener BlipServerEventListener listener Adds the specified listener to the BlipServer void addEventListener BlipServerEventListener listener BlipServerEventFilter filter Adds the specified listener to the BlipServer java lang String getBlipNodeConfigurationGroupNames Returns alist of the configuration names which are currently defined in the server java lang String getBlipNodeGroupNames Returns a list of BlipNode group names which are currently defined in the server BlipNodeHandle getBlipNodeHandle BluetoothAddress blipNodeID Returns a handle to the BlipNode with the specified ID if i
152. eripherals wirelessly and effortlessly Have you ever been to a remote location with a laptop and wanted to use a printer to print out some files If you don t have the right printer driver or the right cable then you ll need to give your file to someone who does have it If that person doesn t have the right program to read your file then you re out of luck no printing for you If you had a Bluetooth laptop and that printer was a Bluetooth printer regardless of the manufacturer then you d have no problem With Bluetooth you can ask the printer for the right driver if you don t have it and then you can print your file with no problem The Power User So what if you re a power user You most likely have a PDA a wireless phone a printer or two a scanner an MP3 player a digital camera and a DV camera The back of your computer probably looks like a rat s nest of wires and cables Some devices you may leave disconnected until you really really need them Bluetooth solves all this by allowing you to have virtually an unlimited number of peripherals wirelessly connected to your computer The only limitation is that you can only have seven active connections at the same time That should be fine because it would be quite rare for you to print scan upload pictures and sync your PDA all at the same time Interoperability Any Device to Any Device In the previous scenario your non Bluetooth enabled devices are definitely not interoperable In o
153. erminalID e getTerminalFriendlyName discovered for the first time on BlipNode blipNodelID terminalLastSeenOnThisBlipNode put terminalID blipNodeID break default System out printin Error only TERMINAL DETECTED events should be received nReceived event Event FRIENDLY_NAMES e getEventID private static BluetoothAddress parseTerminalList final String args int numberOfTerminals args length 1 List of BlipNodeIds used for tracking is built from input in line parameters entered at start up of Tracking application BluetoothAddress trackTheseTerminals null if numberOfTerminals gt 0 trackTheseTerminals new BluetoothAddress numberOfTerminals for int inputParameterCount 0 inputParameterCount lt numberOfTerminals inputParameterCounttt try Make sure it is a valid TerminalID BluetoothAddress trackTheseTerminals inputParameterCount new BluetoothAddress args inputParameterCount 1 catch IllegalArgumentException iae System out printin TerminalId args inputParameterCount is invalid A valid id e g 112233445566 n iae usage return trackTheseTerminals private static void usage System out printin The tracking application requires at least 2 System out p BlipNodes please use BlipManager to specify the BlipNode
154. ers from the list of cached devices Will try to find an echo server in the list of pre known devices devList agent retrieveDevices DiscoveryAgent PREKNOWN if devList null if searchServices devList return record Did not find an echo server in the list of pre known or cached devices So start an inquiry to find all devices that could be an echo server and do a search on those devices try agent startInquiry DiscoveryAgent G IAC this Wait until all the devices are found before trying to start the service search synchronized this try this wait catch Exception e catch BluetoothStateException e System out printin Unable to find devices to search if deviceList size gt 0 devList new RemoteDevice deviceList size deviceList copyInto devList if searchServices devList return record return null This is the main method of this application public static void main String args L2CAPEchoClient client null Validate the proper number of arguments exist when starting this application if args null args length 1 System out printin usage java L2CAPI return Create a new EchoClient object try client new L2CAPEchoClient catch BluetoothStateException e System out printin Failed to
155. ession management a customer may be offered the same e coupon multiple times when passing by a different node in a grocery store In an office building providing wireless network access to Bluetooth enabled clients is a common enterprise Bluetooth application Session management in this scenario is also important so that clients can freely roam around the building without having to reauthenticate when they go in and out of range of different nodes In order to create enterprise Bluetooth applications you need more than just a single Bluetooth device and an API Enterprise Bluetooth applications also require an infrastructure to be in place that will allow your system to be scalable and robust The Ericsson BlipNet The Ericsson BlipNet contains the infrastructure functionality and scalability that will allow developers to create enterprise Bluetooth applications using the Java language An architecture diagram of the Ericsson Blip Net is shown in Figure 11 1 ws eo BlipManager 3 Application mi aiL TCP IP BlipNodes aj Clients Figure 11 1 An architecture diagram of the Ericsson BlipNet Note Although the Ericsson BlipNet allows you to create enterprise Bluetooth applications in Java it does not support the JSR 82 The JSR 82 is oriented toward creating applications where a single Bluetooth device communicates to other devices in a piconet The BlipNet APlis oriented toward managing a network of Bluetooth enabled
156. et you up to speed on how to use the first and only Bluetooth network simulator in which you can execute your JSR 82 compatible code the Rococo Impronto Simulator Note This chapter is intended to provide a brief overview of the concepts of simulation and the Rococo software For more detailed information on how to use the Rococo Impronto Simulator be sure to read the user manual Difference Between a Simulator and an Emulator Is there a difference between a simulator and an emulator Yes definitely An emulator is a software program or sometimes a hardware device that emulates the functionality of another computer system Behind the scenes the emulator translates the instructions of the device being emulated to the machine code of the foreign system Essentially only computers can emulate other computers and due to the translation process emulation works best when a faster computer emulates a slower computer Emulators are handy when you want to run a program but the computing system for which it was originally designed no longer exists or isn t available For instance the Multiple Arcade Machine Emulator MAME project is a popular emulator that allows you to play classic arcade games on your desktop computer PalmSource also makes an emulator that allows you to run different versions of the Palm OS on your desktop computer This can be useful when testing to see if your code is backward compatible with older versions of the Palm OS On
157. ete normally INQUIRY_TERMINATED if the device discovery transaction was canceled by calling DiscoveryAgent cancelInquiry T iD if the device discovery transaction ended normally public void inquiryCompleted int discType synchronized this try this notifyAll catch Exception e The EchoClient will make a connection using the connection string provided and send a message to the server to print the data sent class EchoClient Keeps the connection string in case the application would like to make multiple connections to an echo server private String serverConnectionString The constructor creates an EchoClient object that will allow an application to send multiple messages to an echo server EchoClient String server serverConnectionString server Sends a message to the server public boolean sendMessage String msg L2CAPConnection con null byte data null int index 0 byte temp null try Create a connection to the server con L2CAPConnection Connector open serverConnectionString Determine the maximum amount of data I can send to the server int MaxOutBufSize con getTransmitMTU temp new byte MaxOutBufSize Send as many packets as are needed to send the data data msg getBytes while index lt data length Dete
158. ets and the server responds with a CONTINUE response code The server responds to the final PUT packet with a SUCCESS code Similarly clients are able to retrieve objects from the server by sending a GET request packet If the server accepts the packet it responds with either a SUCCESS or a CONTINUE response code If the server responds with a CONTINUE then the client continues to send a GET request until the server responds with aSUCCESS code The client uses the SETPATH operation in conjunction with a PUT or GET operation in order to change the directory on the server The client can also use the ABORT operation in order to end the session with the server prematurely The client can create an empty file on the server using the CR and it can remove an object from the server using the PUT DELETE operation EATE EMPTY operation Now that you have a pretty good understanding of the overall functionality of OBEX let s take a look at the Java OBEX APIs The OBEX APIs in the JSR 82 The following eight classes and interfaces make up the javax obex package in the JSR 82 API Some of these classes should look somewhat familiar to you namely HeaderSet ResponseCodes and Operation m Authenticator m ClientSession m HeaderSet m Operation m PasswordAuthenticator m ResponseCodes m SessionNotifier m ServerRequestHandler Now let s take a look at some of these cla
159. eturns the type of session that this event is related to ShortUuid getShortUUIDs Returns an array of short UUIDs representing the services supported by the terminal to which this event is related java lang String getTerminalClassOfDevice Returns the class of device of the terminal to which this event is related java lang String getTerminalFriendlyName Returns the friendly name of the terminal to which this event is related BluetoothAddress getTerminalID Returns the Bluetooth device address of the terminal to which this event is related java lang String getTerminallIP Returns the IP address of the terminal to which this event is related Class EricssonMelody public final class EricssonMelody extends java lang Object implements ObexPushObject AnobexPushObject implementation of an Ericsson Melody This class wraps the given melody string in a format understandable by an Ericsson Mobile Phone Package com ericsson blipnet api obex pushobjects Constructors EricssonMelody java lang String melody Constructs an Ericsson Melody push object with a default name NONAME EMY EricssonMelody java lang String melody java lang String name Constructs an Ericsson Melody push object with the name specified Methods byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String getObe
160. evice that could revolutionize the portable gaming industry the Nokia N Gage Figure 1 2 The Bluetooth enabled Nokia N Gage wireless gaming system Devices of the Future So what kind of devices applications or innovations can we expect to see in the future that involve Bluetooth Well here are just a few that we can think of Bluetooth locator system Personalized family car a The new arcade a restaurant lobby The following sections describe these in more detail Bluetooth Locator System Let s start off with a Bluetooth enabled home which means that wherever you go in your home you are within range of the wireless network With a Bluetooth enabled home you have the ultimate locator system All your Bluetooth enabled devices can never be misplaced if they are within the bounds of your home If an item ever gets lost all you need to do is go to your PC and start up the Bluetooth locator system program For basic systems you tell the program what device you are looking for and the device will beep until it is found For advanced systems the Bluetooth locator system will display a map of your house and show you which room has your lost item This solution is ideal for people who always misplace small but essential items like PDAs wireless phones keys TV remotes watches and baby pacifiers Personalized Family Car In this example let s start off with a Bluetooth enabled car With a Bluetooth enabled car all you need to
161. fier Connector open btgoep localhost 1106 name FTP System out printin Waiting for a client connection sn acceptAndOpen server System out printin A Client now connected A service record has now been created and stored in the SDDB of the server device Now let s take a closer loc at the connection URL btgoep localhost 1106 name FTP As you can see we are using a new protocol for communication bt goep which stands for Bluetooth Generic Object Exchange Profile Because this is a server device the address will always be localhost The UUID fc this service is 1106 which is the UUID for OBEX file transfers CROSS SeeTable 4 4 for UUID values for Bluetooth services and their corresponding profiles REFERENCE We also gave a friendly name for this service which is FTP Our file transfer server has extended the ServerRequestHandler class and has overridden the onConnect and onGet methods Here the onGet method will attempt to read the requested file from the local storage and send the file back to the client Obviously the onConnect and onGet methods are only called if the clients send a CONNECT or GET operation to the server The code for the file transfer server is shown in Listing 7 1 Listing 7 1 FTServer java import javax microedition io import java io import javax bluetooth import javax obex public class FTServer extends ServerRequestHandler p
162. file If you ve used a modem before then you should be familiar with the concept of dial up networking The Dial Up Networking Profile allows you to mimic the functionality of a modem Just like the Serial Port Profile some Bluetooth kits come with a driver that will allow your operating system to communicate over the virtual modem as if it were an actual modem see Figure 2 8 As far as the operating system is concerned it s just another modem Note For such an example to work you ll need another Bluetooth enabled device in the area that also supports the Dial Up Networking Profile like a network access point or a wireless phone FAX Profile Using the FAX Profile a Bluetooth enabled computer can send a fax wirelessly to a Bluetooth enabled fax machine or to a Bluetooth enabled wireless phone Headset Profile The Headset Profile is primarily designed for connecting Bluetooth enabled headsets to Bluetooth enabled wireless phones LAN Access Profile A Bluetooth enabled device such as a PC or laptop will use the LAN Access Profile to connect to a network access point connected to a LAN Personal Area Networking Profile The Personal Area Networking Profile is pretty much similar to the LAN Access Profile except it also has support for devices to form ad hoc networks among themselves The PAN Profile also has a requirement that BNEP be present in the underlying protocol stack Cordless Telephony Profile The Cordless Telephony P
163. from a recent inquiry Of course the definition of recent is implementation dependent A PREKNOWN device is a level abov aCACHED device and is one that you frequently communicate with For example let s say that you own a Bluetooth enabled PDA If you have exchanged business cards with another PDA within an hour an implementation may classify that PDA as CACHED However if you own a printe at home and you print to it often from the PDA then an implementation may classify the printer as PREKNOWN Please note that the ret rieveDevices method does not perform a true inquiry for Bluetooth devices and subsequently devices found from this method may not be in the area However this really isn t a problem because the purpose of this method is to quickly give you the references to the devices that you want to connec to The start Inquiry method will guarantee that the device is in the area but it may take a considerable amount of time in order to find the device that you want javax bluetooth DiscoveryListener If you ve worked with event handling in Java then the concept of listeners is not new to you Like all listeners DiscoveryListener is an interface that has a method that is called by the JVM when the desired event occurs If you want to be informed when a Bluetooth device is found by DiscoveryAgent startInquiry then your class needs to implement the DiscoveryListener interface Whenever a Bluetooth device is foun the met
164. ft this part off but we want our custom service to have a name so the actual service record in the SDDB has the following entry T ServiceName serialconn The implementation has also assigned a channel identifier to this service The client must provide the channel number along with other parameters in order to connect to a server 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 You simply call Connector open StreamConnection con StreamConnection Connector open url You obtain the url String thatis needed to connect to the device from the serviceRecord object that you get from service discovery Here s a bit more code that will show you how a Serial Port Profile client makes a connection to a Serial Port Profile server String connectionURL serviceRecord getConnectionURL 0 false StreamConnection con StreamConnection Connector open connectionURL What does a Serial Port Profile client connection URL look like If the address of the server is 0001234567AB then the String that the SPP client would use would look something like this btspp 0001234567AB 3 The 3 at the end of the URL String is the channel number that the server assigned to this service when this service was added to the SDDB L2CAP Connections Unlike RFCOMM connections which are stream oriented L2CAP connect
165. ften written in hexadecimal Objects of the ShortUuid class are immutable once created they cannot change This class provides the equals and hashCode methods for use in connection with the Collection classes Package com ericsson blipnet api bluetooth Fields static int DIALUP_NETWORKING_SERVICE_CLASS_ID Short UUID for the Dialup Networking Profile static int LAN_ACCESS_USING_PPP_SERVICE_CLASS_ID Short UUID for the LAN Access Using PPP Profile static int OBEX_OBJECT_PUSH_SERVICE_CLASS_ID Short UUID for the OPP Profile static int SERIAL_PORT_SERVICE_CLASS_ID Short UUID for the Serial Port Profile static int SERVICE_DISCOVERY_SERVER_SERVICE_CLASS_ID Short UUID for the Service Discovery Server Profile static int WAP_OVER_BLUETOOTH_CLIENT_SERVICE_CLASS_ID Short UUID for the WAP over Bluetooth Client static int WAP_OVER_BLUETOOTH_SERVER_SERVICE_CLASS_ID Short UUID for the WAP over Bluetooth Server Constructors ShortUuid byte shortUuid Constructs a ShortUuid object from a byte ShortUuid int shortUuid Constructs a Short Uuid object from an int ShortUuid java lang String shortUuid Constructs a ShortUuid object from a String Methods boolean equals java lang Object obj Compares this ShortUuid with an Object and returns true
166. functional computing systems that is JSR 82 compliant the Micro Blue Target You should be fully aware of its physical aspects for computational power data connectivity and wireless communication You should also be familiar with HyNetOS the operating system for the Micro Blue Target Due to its small form factor low power requirements and extensibility the Micro BlueTarget is a great device to create fixed wireless systems and proofs of concepts for wireless applications In Chapter 11 we ll explore what it takes to create scalable and robust wireless applications in Bluetooth that can handle more than just seven concurrent users Chapter 11 Enterprise Bluetooth Applications with the Ericsson BlipNet Overview As you have seen in the previous chapters of this book the JSR 82 is a great API for creating Bluetooth applications with the Java language With any vendor implementation of the JSR 82 you can create hundreds of client server peer to peer cable replacement and fixed wireless Bluetooth applications However this API falls short when you need to create enterprise Bluetooth applications So what s an enterprise Bluetooth application Well here are the major qualifications of an enterprise Bluetooth application Capability to handle more than just seven active connections Aconnection range greater than just 30 or 300 ft Centralized communication to the devices also called nodes that comprise your network A means for
167. g fileContent after the whole file gets transferred an empty packet is sent int actualDataSize 1 byte pkt null while actualDataSize fileReader read buffer 1 pkt new byte actualDataSize System arraycopy buffer 0 pkt 0 actualDataSize l2capConn send pkt System out printin Completed sendng body of file fileName sending empty packet signaling end of file l2capConn send new byte 0 fileReader close return true catch IOException e System out println e getMessage return false finally System out printin Closing connection try l2capConn close catch Exception genx public static void main String args throws Exception JPSBluetoothPrintClient client new JPSBluetoothPrintClient client getServices System out println client sendFile args 0 Summary This chapter was probably your first time working with the new Java Print Service APls The JPS is a platform independent printing solution that s new in JDK 1 4 In this chapter you learned about all the steps that are necessary to create a complete JPS application such as identifying the data format searching for print services specifying attributes and creating and submitting print jobs After creating a simple JPS application you learned how to turn your ordinary print service into a Bluetooth enabled print server This chapter demonstrated communication with Bluetoo
168. g of the Government Model Engineering College an institute affiliated with Cochin University of Science and Technology In June 1998 he joined Atinav as a software engineer Presently he is working as a senior technical manager and is managing the Bluetooth related Java products from Atinav About the Technical Reviewer Andrew Stringer was educated at the Dublin Institute of Technology in computer science and software engineering receiving a bachelor of science degree Andrew joined Rococo Software in 2001 as a trainer and consultant in the field of wireless software development Andrew has great experience in developing and delivering courses with J2ME and also with Java APIs for Bluetooth Wireless Technology JABWT Andrew lives in Dublin Ireland Acknowledgments personally want to thank all the people who helped me in writing the book that you re holding Never in a million years would have thought that would be working with Gary Cornell and John Zukowski both of whom are very respected Java authors I m very grateful that Gary and John accepted my proposal way back in January of 2002 For that matter want to thank the rest of the team at Apress including Tracy Brown Ami Knox Kari Brooks and Wanshun Tam More honor however goes to Tracy Many thanks to Andrew Stringer from Rococo for tech reviewing this book never knew that could have been wrong so many times It s good to have an expert at your disposal Bluetooth eq
169. ge return start the echo server with a fictional UUID String url btl2cap localhost 00112233445566778899AABBCCDDEEFF Server L2CAPConnectionNotifier Connector open url ch IOException e System err printin Failed to start service System err printin IOException e getMessage return tem out printin Starting L2CAP Echo Server This server actually runs forever However it can be stopped by terminating the KVM from the command line The server can terminate client connections by setting the client connections public variable end to true like L2CAPEchoServer Client end true le true L2CAPConnection conn null try wait for incoming client connections blocking method class C sta publ conn Server acceptAndOpen here we ve got one L2CAPEchoServer Client start it in a separate thread L2CAPEchoServer Client catch IOException e System out printin I0 l lientProcess extends Thread tic L2CAPConnection clientconn lic boolean end the constructor ClientProcess L2CAPConnection con this clientconn conn this end false new ClientProcess conn start Exception e getMessage n start the communication with the client public void run byte data null rit length System out printin Client is while tend
170. getObexType Returns the mime type of this ObexPushObject void setObexType java lang String mimeType Class ObexGenericObject public class ObexGenericObject extends java lang Object implements ObexPushObject Implements a generic OBEX push object Package com ericsson blipnet api obex pushobjects Constructors ObexGenericObject byte bytes Constructs an OBEX push object representing the specified file ObexGenericObject byte bytes java lang String obexType Constructs an OBEX push object containing the bytes of the specified byte and with the specified filename ObexGenericObject java lang String obexName byte bytes Constructs an OBEX push object containing the bytes of the specified byte and with the specified filename ObexGenericObject java lang String obexName byte bytes java lang String obexType Constructs an OBEX push object containing the bytes of the specified byte and with the specified filename Methods byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String getObexType Returns the mime type of this ObexPushObject void setObexType java lang String mimeType Interface ObexProgressEvent public interface ObexProgressEvent extends Event An event indicating progress of an ongoing OBEX push This type of event is only sent to ObexProgressListeners
171. gh 4 4 if you re still in the dark about the relationship between the SDDB ServiceRecord DataElement and UUID objects Service Registration Before a Bluetooth client device can use service discovery on a Bluetooth server device the server needs to register its services internally That process is called service registration This section discusses what s involved service registration for a Bluetooth device and we ll also give you a rundown of the classes needed to accomplish this Note In a peer to peer application like 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 into your code in order to handle both scenarios of service discovery and service registration Here s a scenario of what s involved in getting your service registered and stored in the SDDB 1 Callconnector open and cast the resulting connection to a StreamConnectionNotifier objec Connector open creates anew ServiceRecord and sets some attributes 2 Use the LocalDevice object and the StreamConnectionNotifier to obtain the ServiceRecord that was created by the system 3 Add or modify the attributes in the ServiceRecord optional 4 Use the StreamConnectionNotifier to call acceptAndOpen and wait for Bluetooth clients to discover this service and connect 5 The system creates a service record in the SDDB Wait until a client connects When the server
172. gth of the object in bytes TIME ISO 8601 68 java util Calendar The time in ISO 8601 format TIME 4 BYTE 196 java util Calendar The time represented as a 4 byte integer DESCRIPTION 5 java lang String A description of the object TARGET 70 byte The name of the service that the object is being sent to HTTP 71 byte The HTTP version 1 x header WHO 74 byte Refers to the peer OBEX application if peers are involved OBJECT CLASS 79 byte The OBEX object class for the object APPLICATION PARAMETER 76 byte Data that represents request and response parameters for the OBEX application You are also free to create your own headers as long as you obey the following guidelines m java lang String object types should have a header ID decimal value between 48 and 63 a byte arrays i e byte should have a header ID decimal value between 112 and 127 a java lang Byte object types should have a header ID decimal value between 176 and 191 a java lang Long object types should have a header ID decimal value between 240 and 255 The OBEX Session Protocol The OBEX Session Protocol specifies all rules and processes for communication between OBEX clients and servers The communication scheme is a simple request response process The client sends a request and the server responds Both requests and responses are sent as packets Clients communicate to the server via eight simple operation
173. gure 10 4 A Bluetooth PDA receiving the status from a fixed wireless commercial system a Bluetooth enabled machine in a manufacturing facility Figure 10 5 A block diagram of the Micro BlueT arget hardware components Figure 10 6 A structural overview of the HyNetOS for the Micro BlueT arget Figure 10 7 The memory map of the Micro BlueTarget End user applications have about 1 5MB of space on the flash disk Figure 10 8 Using the built in functionality of the Micro BlueTarget you can have any Bluetooth device with the LAN Access Profile access the Internet or any other Ethernet based network Figure 10 9 The L2CAPEcho Service Figure 10 10 Using the Micro BlueTarget to create a fixed wireless system Chapter 11 Enterprise Bluetooth Applications with the Ericsson BlipNet Figure 11 1 An architecture diagram of the Ericsson BlipNet Figure 11 2 You can use the BlipNet API and custom J2SE code to access external resources like databases directories and e mail servers Figure 11 3 A single BlipNode Figure 11 4 The BlipManager application Chapter 12 Bluetooth and Jini Figure 12 1 These three entities must exist before a Jini federation is established The federation itself hasn t been formed because the entities don t know anything about each other yet Figure 12 2 The Service Provider discovers the Lookup Service and receives its ServiceRegistrar object The ServiceRegistrar is used to interact with the Lookup Service via
174. h IOException exc System out printin IOException exc getMessage exc printStackTrace System out printin Bluetooth Probably NOT Started Listing 4 3 DeviceProperties java import com jbed bluetooth L import com jbed bluetooth HciTransport import java util Hashtable public public static final in final class DeviceProperties DEFAULT tatic final in ERICSSON public public public tatic final in tatic final in CSR 2 SILICONWAV public static final in public static final in NON SECURE SERVIC public static final in INK Final in final public static public public public public tatic in in int int tic int tatic tatic tatic TRUSTED_ UNTR UNKNOWN A A ED RED 0x4 0x1 0x2 fr NC NDNA NDNA RAM MA MW UW NA SIZE SERVICE TABL DEVICE _ IZE ic final EVICE ic final S D D EVICE NAP_GN_MO DEVIC PANU_MODE DEVICE NGT DATA MTU HEADER _L tic in tic F int maximumServiceRecordCount 691 H 14 Oxffff ll SDP_SERV SD BNI PC maximumAttributeByteCount F R_ THREADS 4 LIENT_T
175. h specification created through the JCP Understanding the JCP The JCP is the Java Community Process and it is the formal procedure to get an idea from a simple concept incorporated into the Java standard This process allows developers and industry experts to shape the future of the Java standard Popular APIs like Java USB Java Real Time Java Printing Java New I O J2ME MIDP 1 0 J2ME MIDP 2 0 JDBC 3 0 EJB 2 0 and even JDK 1 4 all went through the Java Community Process If you want to add some new functionality to the Java language or if you want to suggest a new API or if you think that some new classes should have a package name of java or javax then you need to go through the JCP The Role of the JSR 82 A JSR is a Java Specification Request in the Java Community Process The JSR 82 is the formal JCP name for the Java APIs for Bluetooth When a proposed JSR is approved an Expert Group is formed by the specification lead The specification lead for the JSR 82 was Motorola and together with the JSR 82 Expert Group they created the official Java Bluetooth APIs The following companies participated in the JSR 82 Expert Group Extended Systems a IBM Mitsubishi Newbury Networks a Nokia Parthus Technologies Research in Motion RIM Rococo Software a Sharp Electronics m Sony Ericsson Smart Fusion Smart Network Devices Sun Microsystems Symbian Telecordia Vaultus Zucotto The JSR 82
176. hConnectionException ThisBluetoothConnectionException is thrown when a Bluetooth connection L2C AP RFCOMM or OBEX cannot be established successfully BluetoothStateException TheBluetoothStateExcept ion is thrown when a request is made to the Bluetooth system that the system cannot support in its present state ServiceRegistrationException TheserviceRegistrationException is thrown when there is a failure to add a service record to the local Service Discovery Database SDDB or to modify an existing service record in the SDDB Table 3 2 Classes in the javax obex Package CLASS NAME DESCRIPTION Authenticator This interface provides a way to respond to authentication challenge and authentication response headers ClientSession TheclientSession interface provides methods for OBEX requests HeaderSet TheHeaderSet interface defines the methods that set and get the values of OBEX headers Operation TheOperation interface provides ways to manipulate a single OBEX PUT or GET operation SessionNotifier TheSessionNotifier interface defines a connection notifier for server side OBEX connections PasswordAuthentication This class holds user name and password combinations ResponseCodes TheResponseCodes Class contains the list of valid response codes a server may send to a client ServerRequestHandler TheServerRequestHandler Class defines an event
177. have a full working example of both an OBEX client and an OBEX server let s look at what it takes to use other OBEX operations The SET PATH Operation TheSETPATH operation allows an OBEX client to make a request to an OBEX server to change its current directory The server is not required to obey the request so the server is free to return an error to the client indicating that the request was rejected The exact syntax for ClientSession setPath is public HeaderSet setPath HeaderSet headers boolean backup boolean create To specify the name of the directory that you want to navigate to you must create a HeaderSet with the name set as a header If you wanted to set the path to the previous directory ie cd then backup must be set to true If the directory does not exist but you want it to be created then you must set create to be true The code that follows demonstrates how to create a SETPATH operation HeaderSet folderHdr clientSession createHeaderSet folderHdr setHeader HeaderSet NAME temp HeaderSet resultHdr clientSession setPath folderHdr false true The PUT Operation After creating and sending a CONNECT operation creating a PUT operation is very straightforward as shown in t code presented here hdr con createHeaderSet String filename resume_cv txt setting values hdr setHeader HeaderSet NAM hdr setHeader HeaderSet TYP fileName text plai
178. he time this BlipNode object was created boolean isBlipNodeConnected Checks whether the BlipNode is connected to the server at the time this BlipNode object was created Interface BlipNodeCause public interface BlipNodeCause This interface defines the cause values returned in BlipNode events package com ericsson blipnet api blipnode Fields static int CAUSE_BASEBAND_ERROR Baseband error in BlipNode static int CAUSE_BLIPNODE_BLIPSERVER_PROTOCOL_ERROR BlipNode BlipServer protocol error static int CAUSE_DHCP_ERROR_LAP T DHCP error LAN Profile static int CAUSE HOST STACK ERROR Host stack error static int CAUSE_HOST_TIMEOUT Host timeout static int CAUSE INSUFFICIENT TERMINAL CAPABILITIE gal n Insufficient terminal capabilities static int CAUSE_INTERNAL ERROR Signifies an internal error in the BlipNode which causes a reboot static int CAUSE_LOSS_OF_SIGNAL Loss of signal static int CAUSE MAX CONNECTIONS REACHED Max connections reached static java lang String CAUSE NAMES Friendly names for the cause values static int CAUSE PAGE TIMEOUTI Page timeout ve static int CAUS ELAY AGENT TO DHCP CLIENT SWITCH Relay Agent DHCP Client switch rebooting T n static int CAUS
179. her profiles use this profile for basic connection establishment This is the java lang Object in the Bluetooth Profile realm every profile needs to use the functionality of the GAP Service Discovery Application Profile The Service Discovery Application Profile is a profile that directly interacts with the Service Discovery Protocol SDP layer in the Bluetooth protocol stack This profile is used to find services on Bluetooth enabled devices in the area Serial Port Profile The Serial Port Profile is a profile that interacts directly with the RFCOMM layer in the Bluetooth protocol stack This profile is used to create a virtual serial port on your Bluetooth enabled device For instance some Bluetooth kits come with a driver that will allow your operating system to communicate over the virtual serial port as if it were an actual serial port As far as the operating system is concerned it s just another serial port as shown in Figure 2 8 rote gj eee en Bm lan al ae Eet e Manager and a gt ter age JQR Manage t Dont oen a LW Or o mere J serves and A 7 Figure 2 8 As you can see in Windows 2000 the operating system thinks that COMM10 and COMM11 are actual serial ports Note Of course if you want to connect to another device over the air using your virtual serial port then you ll need another Bluetooth enabled device in the area that also supports the Serial Port Profile Dial Up Networking Pro
180. hod deviceDiscovered is called public void deviceDiscovered RemoteDevice btDevice DeviceClass cod As stated in the preceding section this method is called by the JVM when a remote Bluetooth device is found from an inquiry The RemoteDevice object is a reference to the Bluetooth device found from the inquiry The DeviceClass object which tells you if the remote device is aphone a PC a PDA etc is also provided when this method is called See Table 4 2 for common device classes and their numbers Note ThedeviceDiscovered method may be called more than once for the same Bluetooth device in the vicinity Now that you know all the semantics about discovering devices let s discuss how to find what services if any that these devices offer Service Discovery After you have located devices in the area it would be really nice to see what services those devices offer Of course you can always inspect the DeviceClass object but that may only reveal half the picture Let s say th you want to print a text file Obviously if the DeviceClass indicates that the major device class of the RemoteDevice is a printer then you re all set But what if the major device class is a computer Would it com to mind that you can also print to a computer that is acting as a print server CROSS This is actually a good segue for Chapter 6 In Chapter 6 you ll learn how to convert yoi REFERENCE desktop computer into a wireless print server The service
181. hough not crucial to understanding how the Service Consumer gets a service it s useful to know that a requested service is marshalled on the Lookup Service before being passed to the Service Consumer Basically the service object is flattened and serialized and then served asa file to the Service Consumer Once received the Service Consumer s JVM unmarshalls the object into an instantiation of the service object Once the Service Consumer has the desired ServiceItem it can use the service locally Under the covers the service may communicate back to the Service Provider as shown in Figure 12 7 Lookup Service Servicelten N a Service Consumer Service Provider Data and Signals Servicelten Servicelten k Figure 12 7 Once activated on the Service Consumer the Service Provider s service may communicate directly with the Service Provider device as part of the service offered Integrating Jini and Bluetooth Now that you have a clear understanding of the basics of a Jini federation let s examine the possible scenarios of what s involved when integrating Jini and Bluetooth together All Bluetooth Jini Federation As the name implies in an all Bluetooth Jini federation all the devices participating in the federation are Bluetooth enabled For such a scenario to take place the Bluetooth devices must discover each other and form a piconet Since a requirement of a Jini federation is that the connections between
182. ic int onGet Operation op try HeaderSet hdr op getReceivedHeaders javax obex SessionNotifier The SessionNotifier interface follows the same pattern as all notifiers in J2ME A device that wants to be an OBEX server must implement this interface and call the acceptAndOpen method and wait for clients as shown in the following code SessionNotifier sn SessionNotifier Connector open btgoep localhost 1106 name FTP sn acceptAndOpen serverRequestHandler Once the server accepts a connection from a client it then opens a channel for the client The subclass of ServerRequestHandler that you passed to the acceptAndOpen method is notified of all subsequent requests from the client Now that we ve covered many of the classes of the Java OBEX API let s look at an example that puts these concepts together File Transfer Example In the file transfer example we ll examine the code that s needed to send a file between two Bluetooth devices using the OBEX API of the JSR 82 The server code is less complex than the client code so we ll present that first File Transfer Server Before any clients can connect the server must register the service in the SDDB This is accomplished in the main method as shown here public static void main String args throws IOException FTServer server new FTServer LocalDevice localDevice LocalDevice getLocalDevice SessionNotifier sn SessionNoti
183. ication was released the Bluetooth SIG added four more members 3Com Agere Microsoft Motorola Today the Bluetooth SIG has well over 2 000 members that are all interested in promoting and improving the Bluetooth standard The Radio Spectrum Wireless communication between computers is either in the form of light or radio signals Infrared technology is the common way to conduct short range wireless communications and obviously uses light Conversely Bluetooth technology uses radio signals Table 2 1 gives a list of common everyday items that rely on radio signals for communication As you can see Bluetooth cordless phones 802 11b and 802 11g fall in the 2 4 GHz range Hopefully this will demystify the Bluetooth concept if you are newto all this it s just a radio Table 2 1 Common Radio Frequencies ITEM FREQUENCY RANGE AM radio 535 kHz 1 6 MHz Garage door openers 40 MHz Baby monitors 49 MHz TV channels 2 6 54 MHz 88 MHz FM radio 88 MHz 108 MHz TV channels 7 13 174 MHz 216 MHz TV channels 14 83 512 MHz 806 MHz CDMA cellular phone 824 MHz 894 MHz GSM cellular phone 880 MHz 960 MHz Cordless phones 900 MHz Global Positioning System 1 227 GHz 1 575 GHz PCS cellular phone 1 85 GHz 1 99 GHz 802 11b 2 4 GHz 2 483 GHz 802 119 2 4 GHz 2 483 GHz Bluetooth 2 4 GHz 2 483 GHz Cordless phones 2 4 GHz 802 11a 5 15 5 35 GHz Bluetooth Devices So if a Bluetooth
184. ice List IMPLICIT for int k 0 k lt services length k ServiceLst append services k null ServiceLst addCommand backCommand ServiceLst setCommandListener this display setCurrent ServiceLst if c backCommand display setCurrent deviceLst public void deviceDiscovered RemoteDevice btDevice DeviceClass cod Store the device address in the array which will be used to create the device list the getBluetoothAddress returns the Bluetooth address as a string sf devicef count btDevice Check the type of device so that the appropriate image can be selected try if cod getMinorDeviceClass 0x04 img count Image createImage phone png else if cod getMinorDeviceClass 0x0C img count Image createImage laptop png else img count Image createImage misc png catch Exception e e printStackTrace count public vo id servicesDiscovered int transID ServiceRecord servRecords for int i 0 i lt servRecords length i services i servRecords i getAttributeValue 0x0100 synchronized this this notify public void serviceSearchCompleted int transID int respCode if respClode SERVICE SEARCH ERROR if respCode SERVICE_SEARCH_COMPLETED i i System out println nSERVICE SEARCH ERROR n System out printin nSER
185. ike SUCCESS FAILURE and CONTINUE Good question Well the OBEX SUCCESS response code is mapped to OBEX HTTP OK in the ResponseCodes class And rather than simply having a generic response code for FAILURE there are numerous response codes to indicate what kind of failure has occurred Finally the CONTINUE response will always be handled by your underlying implementation so you should never see it Here is an example of how to use the ResponseCodes class to determine if your PUT operation was a success ClientSession session ClientSession Connector open connectURL Operation op session put null OutputStream out op openOutputStream out write Test getBytes out close if op getResponseCode ResponseCodes OBEX_HTTP_OK System out printin PUT operation is success javax obex ServerRequestHandler TheServerRequestHandler is a very useful class for OBEX servers It includes an event listener that responds to specific OBEX requests made to the server Note This is a class and not an interface so in order to use its functionality you need to extend this class and not implement it This class has the following methods that will be called when incoming client requests contain the corresponding operation m onConnect m onSetPath m onDelete m onGet m onPut After the callback method has been called by the JVM you can obtain the headers from the Operation object as shown here publ
186. in the form of something like com vendor bluetooth bcc Now if you re working with a device that comes with the Java Bluetooth standard like a mobile phone or a PDA then there is a high probability that the BCC would be implemented as a native application on that device According to the Java Bluetooth specification these are the requirements of the BCC a Include base security settings of the device Provide a list of Bluetooth devices that are already known The devices do not need to be within range Provide a list of Bluetooth devices that are already trusted The devices do not need to be within range Provide a mechanism to pair two devices trying to connect for the first time a Provide a mechanism to provide for authorization of connection requests Information contained in the BCC must not be modified or altered other than by the BCC itself Depending upon the JSR 82 implementation that you re using the BCC may need to be packaged and deploye with your application code Stack Initialization Now before you can do anything your stack needs to be initialized Remember a Bluetooth stack has direct access to the underlying 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 Stack initialization sequences can vary and it s heavily dependent upon the underlying OS and Bluetooth radio In some cases in particular with
187. ing toUpperCase if null terminals System out printin nTerminals being tracked for int i 0 i lt terminals length i System out printlin terminals i toString toUpperCase else System out printin Tracking all discoverable devices System out println Nal return new BlipServerEventFilter null new int Event TERMINAL DETECTED blipNodeAddressList terminals private class TrackingEventListener extends BlipServerEventAdapter public void handleConnectionEvent ConnectionEvent e switch e getEventID case Event TERMINAL DETECTED BluetoothAddress terminalID e getTerminalID BluetoothAddress blipNodeID e getBlipNodeID if terminalLastSeenOnThisBlipNode containsKey terminalID Terminal has already been discovered before so has it moved if terminalLastSeenOnThisBlipNode get terminalID equals blipNodeID System out println Terminal terminalID e getTerminalFriendlyName moved from BlipNode BluetoothAddress terminalLastSeenOnThisBlipNode remove terminalID to BlipNode blipNodeID terminalLastSeenOnThisBlipNode put terminalID blipNodeID else Terminal stays on the same BlipNode Do not do anything else This is the first this terminal is seen on the syste System out println Terminal t
188. ing a request to server for file Hello txt hdr con createHeaderSet hdr setHeader HeaderSet TYP hdr setHeader HeaderSet NAM Operation op con get hdr text vCard pi Hellestxt 5 H F H The server is now sending the file InputStream in op openInputStream Writing the file from server to local file system StreamConnection filestream StreamConnection Connector open file name HelloFile txt mode w OutputStream out filestream openOutputStream cead and write the data int data in read while data 1 out write byte data data in read send the DISCONNECT Operation con disconnect cleanup op close in close out close catch IOException e System out printin e getMessage public void inquiryCompleted int discType System out println Inquiry completed UUID uuids new UUID 1 uuids 0 new UUID 1106 true try if btDev null System out printin No device has been discovered hence not worth proceeding exiting System exit 1 System out println Now searching for services a mJy agent searchServices attrSet uuids btDev this catch BluetoothStateException e System out printlin e getMessage public static void main String args throws IOException FTClient client new FTClient More on Operations Now that we
189. ing the HYMON utility Note The HyNetOS is a multilanguage multitasking embedded operating system that can run native C applications and Java apps at the same time In order to resolve conflicting requests between native lt Java applications that want to utilize the Bluetooth stack and radio Smart Network Devices created a centralized entity called the Bluetooth Service The Bluetooth Service in JSR 82 vernacular is called 1 Bluetooth Control Center BCC As mentioned in Chapter 4 the Bluetooth Control Center doesn t necessarily have to be a Java application and in the case of the Micro BlueT arget the Bluetooth Con Center is a native application For the Micro BlueTarget you can initialize and control the Bluetooth C Center via configuration files The Wireless Network Access Point Let s say that you have a Bluetooth enabled device like a PDA or laptop and want to use it to access the Intern traditional LAN access point refer to Figure 10 8 With the Micro BlueTarget you re already halfway there anc Java coding is needed Ed 9 CEEE Ethernet Ez ere Line Internet POA Micro BlueTarget Network Hub Wwe Figure 10 8 Using the built in functionality of the Micro BlueTarget you can have any Bluetooth device witl LAN Access Profile access the Internet or any other Ethernet based network So in order to accomplish this with the HyNetOS all you need to do is to edit the parameters in a configuration BTAUTOLAN CFG The contents
190. intin Length devList length If we found a service record for the cable replacement service t we can end the search if record null System out printin Record is not null return CEUS try System out printin Starting Service Search on int trans agent searchServices null System out printin Starting Service Search addToTransactionTable trans catch BluetoothStateException e Failed to start the search on this device System out printin BluetoothStateException Determine if another search can be started If a service search to end synchronized this serviceSearchCount tt System out printin maxServiceSearches serviceSearchCount serviceSearchCount System out println if maxServiceSearches System out println try Waiting this wait catch Exception e System out printin Done Waiting devList i getBluetoothAddress searchList serviceSearchCount i devList i E trans try another devic e getMessage not wait for maxServiceSearch serviceSearchCoun i Wait until all the service searches have completed while serviceSearchCount gt 0 synchronized this try this wait catch Exception e if record null System out printin Record is not null return true
191. ion and the user is given the choice to either start the service indicated by the URI immediately or postpone the Service Indication for later handling If the Service Indication is postponed the client stores it and the end user is given the possibility to act upon it at a later point of time Objects of the WapServiceIndication class are immutable once created they cannot change Package com ericsson blipnet api obex pushobjects Fields static byte DELETE The WAP Service Indication s received on the terminal with a given ID must be deleted static byte SIGNAL_HIGH Indicates that the WAP Service Indication must be presented as soon as the implementation of the terminal allows that to be carried out in a non user intrusive manner or earlier if considered appropriate which may result in a user intrusive behavior static byte SIGNAL_LOW Indicates that the WAP Service Indication must be postponed without user intervention static byte SIGNAL_MEDIUM Indicates that WAP Service Indication must be presented as soon as the implementation allows that to be carried out in a non user intrusive manner static java lang String TOKENIZED_MEDIA_TYP E Defines the tokenized form of the WAP Service Indication Media Type Constructors WapServiceIndication java lang String uri java lang String id byte action java lang String contents Constructs a WapServiceIndication WapServiceIndic
192. ions are packet oriented Before we cover how to create L2CAP connections we ll briefly cover a new concept called Maximum Transmission Unit MTU We ll also cover the classes needed in order to create L2CAP connections L2CAPConnect ion and L2CAPConnectionNotifier Maximum Transmission Unit Because of the fact that the L2CAP layer sends data in packets the official Java Bluetooth API gives you the flexibility to control how large the packets can be The default MTU is 672 bytes but you can attempt to negotia a larger MTU in your connection URL strings Here s why we say attempt If the client indicates that it can receive data in packet sizes of 10MB and the server is only capable of sending data at 1kB then there s no rea problem the client ll get its data in 1kB packets Now on the other hand if the server indicates that it s sending data in 10MB size packets and the client is only capable of handling 1kB packets then the transmission will fai horribly In order to find out the largest packet size that you can receive from a L2CAP connection just run the following piece of code LocalDevice local LocalDevice getLocalDevice String receiveMTUmax local getProperty bluetooth 1l2cap receiveMTU max L2CAP Server Connections Following is the code that a L2CAP server uses to open a connection to aclient L2CAPConnectionNotifier notifier L2CAPConnectionNotifier Connector open url L2CAPConnection con L2CAPConnection
193. is the Micro BlueTarget s system monitor console On the PC this text based monitor can be used to c the file system display directories and set network settings such as the IP address netmask gateway etc T HYMON utility can also be used to start Java applications on the device At the system prompt simply type kvm myapp to start up myapp class on the device HYTRACE HYTRACE is the Micro BlueT arget s system trace window Stacktrace messages and output from your System out println statements in your Java code will appear here Programming the Micro BlueTarget In order to start developing wireless applications for the Micro Blue Target you first need to set up your develop environment Here are the steps that are involved 1 Connect your Micro BlueT arget board to your PC using a crossover Ethernet cable 2 Configure your Micro BlueT arget s IP network parameters using the HYMON utility 3 Format the Micro BlueT arget s flash disk using the HYFLASH utility 4 Create the necessary configuration files and transfer them to the Micro BlueTarget s flash disk These steps are all explained in detail in the Micro BlueT arget Starter Kit documentation After you compile anc preverify your code just FTP the corresponding class files for your application to the Micro Blue Target and hit tl button If your app is specified in the JSTARTUP INI file then it will automatically start up otherwise just start application manually us
194. iscovery 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 in the Java Bluetooth API see what s out there Which Bluetooth devices should use device discovery Well if you are planning to use a peer to peer applicatie in Bluetooth like two PDAs in a chat session then either device would use device discovery to find the other device If you are planning to use a client server type application like printing from a lap top to a printer then th client is most likely to perform device discovery It doesn t make sense for the printer to constantly look for devices that want to print something Now let s take a look at the two classes needed in order for your Bluetooth device to discover remote Bluetoott devices in the area DiscoveryAgent and DiscoveryListener javax bluetooth DiscoveryAgent After getting a LocalDevice object the most logical next step for device discovery is to instantiate the DiscoveryAgent object You accomplish this task by calling LocalDevice getDiscoveryAgent LocalDevice localdevice LocalDevice getLocalDevice DiscoveryAgent discoveryagent localdevice getDiscoveryAgent When you want to discover other Bluetooth devices in the
195. isplay the services that it offers see Figure 5 8 DefaultColorPhone MR E3 Figure 5 8 The Piconet Browser now displays the services offered by the remote device Listing 5 3 shows the code for the Piconet Browser Listing 5 3 PiconetMIDlet java import javax microedition midlet import javax microedition ledui import javax bluetooth import java io import javax microedition io import com atinav bce public class PiconetMIDlet extends javax microedition midlet MIDlet implements CommandListener DiscoveryListener private LocalDevice localDevice null private RemoteDevice device null private DiscoveryAgent discoveryAgent null private Command exitCommand The exit command private Command srchCommand The search command private Command backCommand private Display display The display for this MIDlet private Form frm private List deviceLst private List ServiceLst int count 0 private String dev null private Image img null private String services null public void startApp display Display getDisplay this exitCommand new Command Exit Command EXIT 1 srchCommand new Command Search Command SCREEN 1 backCommand new Command Back Command BACK 1 frm new Form Piconet Browser frm addCommand srchCommand frm addCommand exitCommand frm setCommandListener this display setCurrent frm
196. java lang String address methods boolean authenticate boolean authorize javax microedition io Connection conn boolean encrypt javax microedition io Connection conn boolean on boolean equals java lang Object obj java lang String getBluetoothAddress java lang Stri static RemoteDevice getRemoteDevice javax microedition io Connection conn int hashCode boolean isAuthenticated boolean isAuthorized javax microedition io Connection conn boolean isTrustedDevice ng getFriendlyName boolean alwaysAsk Interface ServiceRecord fields static int AUTHENTICATE ENCRYPT static int AUTHENTICATE NOENCRYPT static int NOAUTHENTICATE NOENCRYPT methods int getAttributeIDs DataElement getAttributeValue int attrID java lang String getConnectionURL int requiredSecurity boolean mustBeMaster RemoteDevice getHostDevice boolean populateRecord int attrIDs boolean setAttributeValue int attrID DataElement attrValue void setDeviceServiceClasses int classes Class ServiceRegistrationException constructors ServiceRegistrationException ServiceRegistrationException java lang String msg Class UUID constructors UUID long uuidValue UUID java lang String uuidValue boolean shortUUID methods boolean equals java lang Object value int hashCode java lang String toString Appendix B javax obex This ap
197. jndael The encryption key is simply a code that is used by the algo encrypt the data In symmetrical encryption the same key is used to encrypt and decrypt the data In asymmetr encryption however two keys are used to encrypt and decrypt the data Note We won t talk about asymmetrical encryption any further because Bluetooth uses symmetrical encryr encrypt its data transmissions Now let s look at a quick example Listing 9 1 shows some information that needs to be cryptographically protec transmitted from a Bluetooth enabled cash card Listing 9 1 Bank Account Information Bank Name SDH Bank Account Name Bruce Hopkins Account Number 123456789 Account Balance 0 03 Note Of course we re protecting the bank account number not the balance When the encryption key as shown in Listing 9 2 and the CAST algorithm are applied to the data then sensitiv account information will get encrypted as shown in Listing 9 3 Listing 9 2 A1024 Bit Encryption Key mQGiBD12ZRx4RBADgiQLiScTmdxd5aMvRIZbcmSsAzwXWtEBwarMO6xR4SDgp ji0 KaU02yOD08XxMA2k 9yvaOXGpKK6UrTeaqMF 9vKyy2 6Sur3eMt JNxbPJok2xXWgcZj hFCYZjG1 wRbx60sf xtWSeuhHyKENGhp352 rByvTFOKSEMf2txYZLOOQCg 0al rgcZTOQyhOWufgMIEIO21dED A3i5oKtibyN2tl0aJpyxFe NFL5uwbIjyWAndEN 2rdhOih7fOhNgVVVm6MGuNu laD5M576JSEngyQexaG4G7 JCOPE1Vk79 EJa6eku ebAaPeg5osCHUAsbUD3lvuxSK8gGsMylxtOgid2gCusS52HDaUVAnvIt9ojpMnOPrz ZrgzZBACZANCzZ0Z RNkYP5Oech UWFgboboPROZ4VbilUFvoZ1 B8auxSvYueXjAuc
198. l RemoteDevice btDev null ceURL null L2CAPConnection 12capConn null luetoothPrintClient throws BluetoothStateException local LocalDevice getLocalDevice agent local getDiscoveryAgent agent startInquiry DiscoveryAgent GIAC this synchronized this Waiting for Device Inquiry to be completed try this wait catch Exception IntE System out printin IntE getMessage public void deviceDiscovered RemoteDevice btDevice DeviceClass cod if 01111437 btDev b System out pr 8000 indexOf btDevice getBluetoothAddress gt 1 tDevice System out printin Assigned intin Device discovered btDevice getBluetoothAddress public void servicesDiscovered int transID ServiceRecord servRecord System out pr for int i 0 serviceURL intln Discovered a service i lt servRecord length i servRecord i getConnectionURL Servic System out eRecord NOAUTHENTICATE NOENCRYPT true println The service URL is serviceURL public void serviceSearchCompleted int transID int respCode System out printin Service search completed ate ay synchronized this Unblocking the wait for Service search complete try this notifyAll catch Exception IntE System out printin IntE getMessage public void inquiryCompleted int discType S
199. l fail Figure 9 5 shows that the authentication process is a success Device Atkiress 191014978000 Device Name ATINAV Do you want to authorize this remote devic SILIETOOT onir enter Daka cose Figure 9 5 The authentication process has succeeded pagre aro sy mt In this example the encrypt parameter in the connection URL was initially set to false in order to show you how easy it is to capture unencrypted data while in transit Figure 9 6 shows the Mobiwave BPA D10 sniffing the data transmission pom Sh U SSeS Posner IER ze v e ERT Fel paken man DODD 5 bodi Figure 9 6 You need to be very careful if you re sending sensitive data unencrypted between Bluetooth devices because it can be captured by a third party using a Bluetooth Protocol Analyzer Now let s see what happens when we set the encrypt parameter to true in the connection URL The results are shown in Figure 9 7 Copturing New Pr BPA 010 Me CR Ssd Yow DPA binis CatueOete Oocytes eb IE 2 ORs mi TO eg esas ix z Pera Li encst ker Ok OON 7D AM YHE ETF ms mg k DOO 196 AM Pht 43 Ok MOC Fm AMT Per 44 LIMP stert_encaypton_reg Ok OOH 4AM DMTTRARTS OT EFT gt Ent E j ke Ck 00c ee AM ii freA St Ps wE Ok OOc Av Pet 4 j Ck 00c AM lt Pd 1 j Ik OIO AM e a 0 Pr _ Pet 43 ke 0000c ed AM Pet SO Ok OOC tem AM Pa 5 OR OOC ce AM
200. les to exist Take a look at Figure 2 9 and see how the Bluetooth profiles are dependent upon each other for functionality Generic Access Profile Service Discovery Personal Area Application Profile Networking Profile Cordless Phone Profile Hard Copy Cable Haman Interface Intercom Profile Replacement Profile Device Profile pe Serial Port Profile Generic Object Exchange Profile Dial Up Networking Profile File Transfer Profile FAX Profile Object Push Profile Headset Profile Synchronization Profile LAN Access Profile Basic Imaging Profile oil Hands Free Profile Basic Printing Profile J Figure 2 9 Bluetooth profile interdependencies For example in order for a PDA vendor to say that it supports the Synchronization Profile for its new Bluetooth enabled BJL 200 PDA it also must support the Generic Object Exchange Profile Serial Port Profile and Generic Access Profile because the Synchronization Profile cannot function without them If a phone manufacturer claims that its new Bluetooth enabled TLJ 50 headset supports the Headset Profile then it must also include the Serial Port Profile and the Generic Access Profile Bluetooth Profiles vs J2ME Profiles 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 th
201. lications with the JSR 82 more secure You learned about how to use the APls in the JSR 82 in order to enable authentication authorization and encryption in your Bluetooth applications This chapter also gave you an introduction to the Mobiwave BPA D10 Protocol Analyzer So far we have used the JSR 82 in order to make client server peer to peer and cable replacement wireless applications In the next chapter we ll take a look at the SND Micro BlueTarget in order to make fixed wireless applications using the JSR 82 Chapter 10 Wireless Embedded Systems with the Micro BlueTarget So far this book has taken mainly a software based approach to things and rightfully so since the JSR 82 is a software specification about controlling Bluetooth devices with the Java language In the past Bluetooth device manufacturers envisioned their devices to be programmed in a native language like assembly or C and making a Java interface to their devices was pretty much an afterthought In this chapter we re going to take a look at a device that was developed with the JSR 82 in mind the Micro Blue Target from Smart Network Devices http www smartnd com What Is the Micro Blue Target So what is the Micro Blue Target and what can it do The Micro Blue Target is a fully self contained computer that includes a Bluetooth radio a Bluetooth stack Bluetooth profiles an operating system a J2ME VM and the JSR 82 libraries Figure 10 1 shows the Micro BlueT a
202. llustrates how the Mobiwave Protocol Analyzer intelligently decrypted data packets on the fly d a AaS f 7 a Ce En LE t au lt PRT Cj M up f f uy 4 T f N s I Please note that the SmartDecrypt feature of the BPA D10 does not illustrate any of the limitations or shortcomings of Bluetooth s wireless encryption capabilities Prior to decrypting the Bluetooth encrypted packets successfully the following information must be available The slave or client BD address that is involved The PIN that is used during the pairing or bonding session When the pairing or bonding session is carried out Confirmation of a good capture of the pairing or bonding session If any of this information is missing or incomplete the decryption will not be successful Information such as when a pairing or bonding session is made is a rare and random event Furthermore during the capturing of a pairing or bonding session many things could go wrong due to interference over the air or Bluetooth devices being out of range Bluetooth s encryption mechanism is not easily breached or compromised Java developers can further mitigate this risk by creating their own symmetric or asymmetric encryption routines by using the libraries from the JCE Java Cryptography Extension or from the Bouncy Castle at http www bouncycastle org Summary This chapter introduced you to the security measures that you can employ to make your Bluetooth app
203. lt 1 usage BluetoothAddress trackTheseTerminals parseTerminalList args System out printin Starting Tracking application System out println Tracking tracker new Tracking args 0 trackTheseTerminals System out printin Tracking application started Note Please see the Tracker java example in the examples directory of the BlipNet SDK for a more detail code explanation of the Tracker example Summary This chapter gave you an introduction to the concept of enterprise Bluetooth applications At this point you should understand the scenarios where enterprise Bluetooth applications are best suited and the components that are needed to create them As you have seen enterprise Bluetooth applications cannot be built with just a single Bluetooth device and an API Using the Ericsson BlipNet developers have the API tools and infrastructure in place in order to create scalable and robust enterprise Bluetooth applications In the final chapter of this book we ll examine how to network Bluetooth devices in a decentralized manner and create a Jini federations among Bluetooth devices Chapter 12 Bluetooth and Jini Overview Well you ve made it to the last chapter of the book By now you should be fully aware of the capabilities of Bluetooth technology with respect to Java As we stated in Chapter 4 the basics of any Bluetooth application consist of a Stack initialization a Device management
204. m using Java and the Ericsson BlipNet Chapter 12 Bluetooth and Jini In the final chapter of the book we provide an overview of Jini network technology and describe how to implement Jini and Bluetooth together Appendix A javax bluetooth Appendix A is a handy reference that contains all the method signatures of the javax bluetooth API Appendix B javax obex Appendix B is a handy reference that contains all the method signatures of thejavax obex API Appendix C Java Bluetooth Development on the PalmOS Platform Appendix C provides a quick overview of howto get started creating Java Bluetooth applications on the Palm OS platform Appendix D BlioNet 1 1 API Appendix D contains full descriptions of the classes exceptions and interfaces that comprise the BlipNet API This appendix will be really useful to have on hand when developing BlipNet applications Intended Audience So who are you This book really has two audiences If you re a Java developer then this book assumes that you re an intermediate Java developer with little or no experience with Bluetooth You ll get the most out of this book if you ve written a few Java classes on your own especially J2ME applications If you re a Bluetooth developer then this book becomes useful to you after Chapter 2 If you ve never used Java before then we d suggest that you read the first few chapters of a J2ME book before you read this book The Code The source code for this book is a
205. mentation automatically generates this attribute and changes its value when any modification occurs with this service record ProtocolDescriptorList is a data sequence of UUIDs with optional parameters or protocol specific values with an attribute ID of 0x0004 Once again the SDP implementation automatically generates this attribute based on the protocol described in Connection URL If the protocol is bt 12cap then ProtocolDescriptorList contains one protocol descriptor for L2CAP in addition to its Protocol Service Multiplexer PSM value If the protocol is bt spp then the ProtocolDescriptorList contains two protocols L2CAP and RFCOMM in addition to the RFCOMM server channel If the protocol is bt goep at in this example then the ProtocolDescriptorList contains three protocols L2CAP RFCOMM and GOEP ServiceDatabaseState is a 32 bit unsigned integer with an attribute ID of 0x0201 Every modification t the SDDB affects the value of this attribute and the SDP implementation will automatically take care of this for you ServiceName is the friendly name by which the services are known to the devices in the vicinity In this example the service name is FTP File Transfer Client Now in order to access the File Transfer server we must first perform device discovery and service discovery lil we always do in Bluetooth applications In addition to that in our serviceSearchCompleted method we create our Operations and Heade
206. mmunicate wirelessly from your PC the host and you have a Bluetooth device the controller attached to your USB port then you ll need a layer that can understand the USB calls and send that information to the upper layers of the stack Everything voice and data passes though the Host Controller Interface Logical Link Control and Adaptation Protocol L2CAP The Logical Link Control and Adaptation Protocol is the core layer of the stack through which all data must pass L2CAP boasts some powerful features like packet segmentation and reassembling of data as well as protocol multiplexing If you are trying to pass a very large packet of data L2CAP breaks up the packet and sends smaller ones Conversely L2CAP also reassembles segmented packets when accepting data With protocol multiplexing L2CAP can accept data from more than one upper protocol at the same time like SDP and RFCOMM Only data passes through the L2CAP layer audio links have direct access to the Host Controller Interface Service Discovery Protocol SDP A Bluetooth device uses Service Discovery Protocol in order to discover services What s a Bluetooth service A good example would be a Bluetooth printer A Bluetooth printer will publish itself with a message such as am a printer how can help you If you have a document and you want to print it then you would use the Service Discovery Protocol to find a printer that offers a printer service in your range RFCOMM
207. n TG F aj wl F aj creating and sending the PUT Operation Operation op con put hdr sending the BODY OutputStream writeStrm op openOutputStream StreamConnection strmCon StreamConnection Connector open file name fileName mode r InputStream readStrm strmCon openInputStream byte block new byte 512 int dataSize 1 while dataSize readStrm read block 1 writeStrm write block 0 dataSize readStrm close setting final bit and sending the END OF BODY HEADER writeStrm close Summary OBEX which stands for OBject EXchange is a powerful transport agnostic communication protocol that allows the transmission of objects between clients and servers The OBEX protocol is an adopted protocol in the Bluetooth specification and originally gets its roots from the IrDA specification This chapter helped you to get familiar with many of the concepts of the OBEX semantics including headers operations and response codes This chapter gave you an introduction of the classes in the javax obex API and also provided a working example on how to send files between wireless devices OBEX opens the door to a world of powerful wireless applications by providing Bluetooth developers with the ability to send files between devices In the next chapter we ll change gears a bit and discuss how to simulate a Bluetooth network Chapter 8 Using a Bluetooth Sim
208. n two parts the OBEX Object Model and the OBEX Session Protocol The Object Model provides the definition of OBEX objects and information on how to transfer them The Session Protocol defines the handshaking that needs to occur between the client and the server when transferring objects between devices Let s look at OBEX Object Model and Session Protocol in more detail The OBEX Object Model In the OBEX Object Model all the details about an object are represented as attributes called headers Each header will contain information about the object i e the name of the object or the object itself The Object Model defines headers as one byte for the header ID and one or more bytes for the header s value A typical OBEX header is illustrated in Figure 7 2 One Byte One or More Bytes mnd Figure 7 2 An OBEX header The OBEX Object Model has defined 17 headers for OBEX object attributes However the official Java OBEX specification uses only 12 of them as constants in the interface java obex HeaderSet These constants are listed in Table 7 1 Table 7 1 OBEX Headers in the java obex HeaderSet Interface HEADER ID NAME HEADER JAVA TYPE DESCRIPTION ID DECIMAL VALUE COUNT 192 java lang Long The number of objects to be sent NAME 1 java lang String The object s name usually used as the filename TYPE 66 java lang String The type of the object like text plain LENGTH 195 java lang Long The len
209. nce Implementation 36 RISC DSP 32 bit CPU Hyperstone 183 185 3 RMS Record Management System 79 logical representation of 80 for persistent storage 79 80 Rococo Impronto Simulator 139 152 Index S Scatternets Bluetooth 31 SDDB Service Discovery Database 58 60 connection URLs and 130 registering and storing services in 66 service records in 59 service registration in 127 SDP Service Discovery Protocol 20 SDP layer 24 58 SearchServices method 63 64 Security 155 178 authentication 156 158 encryption 159 163 server authorization 158 159 Security administration BlipManager 231 Security client attempting to connect to server 171 Security example 163 178 Security measures 155 163 Security server prompting user for PIN 172 waiting for client to connect 170 SelectService method 63 64 client connections with 69 70 server connections with 68 69 Server authentication 156 157 Server authorization 158 159 Server connections with Serial Port Profile 68 69 Server encryption 161 162 ServerApp java listing 163 165 ServerRequestHandler class 126 128 268 ServerRequestHandler methods 126 Service Consumer lifecycle Jini 249 253 Service Consumers Jini 245 249 253 Service discovery 58 65 88 91 Service Discovery Application Profile 24 58 Service discovery process for a PDA 60 Service Providers Jini 245 lifecycle 24 7 249 and Service Consumer 253
210. nection url connectionURL if connectionURL null synchronized this this notify break This function notifies the Thread waiting in main if a service search is terminated i e if the responsecode is SERVICE_SEARCH_COMPLETED or SERVICE_SEARCH_NO_RECORDS public synchronized void serviceSearchCompleted int transID int respCode if respCode SERVICE_SEARCH_ERROR System out printin nSERVICE_SEARCH_ERROR n if respCode SERVICE SEARCH COMPLETED System out printlin nSERVICE SEARCH COMPLETED n if respCode SERVICE SE n a RCH_TERMINATED System out printin ERVICE_SEARCH_TERMINATED n if respCode SERVICE EARCH_NO_ RECORDS synchronized this this notify System out printin n SERVICE_SEARCH_NO_RECORDS n if respCode SERVICE_SEARCH_DEVICE_NOT_REACHABLE System out printin n SERVICE_SEARCH_DEVICE_NOT_REACHABLE n uur Once the device inquiry is completed it notifies the Thread that waits in the public synchronized void inquiryCompleted int discType this notify StreamConnection getconnection throws IOException return
211. nfiguration Next we ll add a brief discussion about its software configuration by looking at the operating system and its Java implementation Finally we ll round up the chapter with some information on how to start the development process with this device by providing some example code The Micro BlueTarget Hardware Configuration Figure 10 5 is a block diagram that describes the interrelationship of the hardware components that comprise the Micro BlueTarget Serial Port Main CPU Bus Bluetooth Serial Dual Baseband 16550 Controller UART gt 2 MB Flash Host Firmare File Systen 1 MB Flash Bluetooth Firmaare 8 MB SDRAM 10 100 Main Ethernet Ethernet MBit Memory Port Magnetics Ethernet Controller Expansion Bus Connector Figure 10 5 A block diagram of the Micro BlueTarget hardware components The Micro BlueT arget is based upon the 32 bit RISC DSP embedded micro processor architecture from Hyperstone AG http www hyperstone com Smart Network Devices chose this architecture primarily because of its extremely low gate count the CPU itself consists of only just 35 000 gates which equates to its low power consumption In the future this opens the door for the possibility of smaller form factor solutions even System on Chip SoC architectures The Bluetooth baseband controller is a BlueCore 01b from CSR see Figure 2 2 which is interfaced through a standard 16550 compatible UART devic
212. ng String toString Returns a String representation of this WapServiceLoading Index Numbers 1 Wire Dallas Semiconductor 254 255 1 Wire interface 254 1 Wire sensor controller 255 2 4 GHz frequency band 1 3Com USB Bluetooth module 14 3Com Wireless Bluetooth Printer Adapter 97 802 11b vs Bluetooth 1 3 1024 bit encryption key 160 161 Index A AcceptAndOpen method 127 Add New Slave dialog box 177 AddEventListener method 234 235 Adopted protocols explained 20 Airports 226 All Bluetooth Jini federation 252 254 Antennae on HP iPAQ 5400 series Pocket PC 4 Apache Ant build utility 141 Application development with Micro BlueTarget 187 224 Application manager 78 Arcade in restaurant lobby 9 Asymmetrical encryption 159 Asynchronous event handler 187 Atinav Bluetooth SDK 47 83 105 Atinav SDK stack initialization code 47 Attributes of service records 59 60 Authenticate parameter of connection URL 156 157 162 Authentication 156 158 173 with LAN access point 192 over L2CAP connection 163 Authentication request client 157 Authentication request Server 156 Authenticator interface javax obex 265 Authorization Bluetooth server 158 159 163 Authorization over L2CAP connection 163 Authorize parameter of connection URL String 158 Authorize method of RemoteDevice class 158 Index B Bank account information listing 160 Bank account information encrypted
213. nment Figure 8 7 The server has sent a message and the client responds Figure 8 8 The client receives a message and sends a reply Chapter 9 Bluetooth Security Figure 9 1 The Mobiwave BPA D10 Bluetooth Protocol Analyzer Figure 9 2 The security server is waiting for the client to connect Figure 9 3 The security client is attempting to connect to the server Figure 9 4 The security server prompts the user to enter a PIN for the application Figure 9 5 The authentication process has succeeded Figure 9 6 You need to be very careful if you re sending sensitive data unencrypted between Bluetooth devices because it can be captured by a third party using a Bluetooth Protocol Analyzer Figure 9 7 With encryption enabled the Protocol Analyzer is still able to capture the data transmission however the data is corrupted Chapter 10 Wireless Embedded Systems with the Micro BlueTarget Figure 10 1 The Micro Blue Target standard version is a small form factor embedded system with a board outline of just 3 25 9 cm This is a great solution for OEMs that want to make their devices Bluetooth enabled Figure 10 2 The Micro BlueTarget Starter Kit uses a standard Micro BlueT arget and adds RS 232 and Ethernet ports which is ideal for developers who need to create quick prototypes and proofs of concepts Figure 10 3 A Bluetooth phone utilizing the services of a fixed wireless consumer system a Bluetooth enabled vending machine Fi
214. nodes where each node has the capability to interact with Bluetooth enabled clients BlipNet Architecture The core part of the BlipNet system is the BlipServer The BlipServer itself is not Bluetooth enabled at all It does however have a direct TCP IP connection to each of the BlipNodes which are Bluetooth enabled and controls them via Java RMI In order to create your enterprise Bluetooth applications you write J2SE classes that interface with the BlipNet API Now since you re writing J2SE code here you may realize that there s nothing preventing you from accessing external resources on behalf of your Bluetooth enabled clients In fact that s the whole point of it Using the Ericsson BlipNet external resources such as databases LDAP directories Web servers and e mail servers are all available at your client s disposal as long as you can access them via a Java API This is reflected in Figure 11 2 eS i W re T 1 i Et 8 e A J WACH gt Database Email LDAP gn A Server Server Server BlipServer EE azy TCP IP BlipNodes Le 1S Clients Figure 11 2 You can use the BlipNet API and custom J2SE code to access external resources like databases directories and e mail servers BlipServer The BlipServer does not require any specialized hardware and can run on either Windows or Linux operating systems The statistics on the BlipServer are pretty impressive a Pentium 400 MHz comput
215. nology One drawback to infrared is that the devices involved must be a few feet apart and most importantly the infrared transceivers must see each other eye to eye If either of those conditions are not met then the transmission will fail Bluetooth overcomes the first limitation by having a nominal range of about 10 meters 30 feet Bluetooth overcomes the second limitation because it works like a radio so transmissions are omnidirectional Consequently there are no line of sight issues when communication occurs between two Bluetooth devices Bluetooth vs 802 11b If you ve heard of Bluetooth before then you ve certainly heard of 802 1 1b the wireless LAN protocol another wireless communication protocol Bluetooth and 802 1 1b were created to accomplish two different goals although both technologies operate in the same frequency band 2 4 GHz Note Having both technologies operate at the same frequency range does not mean they ll interfere when placed in range of each other according to a Forrester Research study conducted in 2001 Go to http www forrester com for details on that report The goal of wireless LAN 802 11b is to connect two relatively large devices that have lots of power at high speeds Typically this technology is used to connect two laptops within 300 feet at 11 Mb s This technology is also useful for network administrators who want to extend their LAN to places where it is either expensive or inconvenient to run
216. ocol L2CAP Service Discovery Protocol SDP a RFCOMM a Telephony Control Protocol Specification TCS BIN a Wireless Access Protocol WAP m Object Exchange OBEX a Bluetooth Network Encapsulation Protocol BNEP Human Interface Device Protocol HID OBEX WAP woe TO f Ip ip tcp PPP Ji IP RFCOMM sor KID BNEP Tes 4 A EA Fi gt Logical Link Control and Adaptation Protocol L2CAP Host Controller Interface HCI Figure 2 7 The Bluetooth protocol stack Note Now if you re familiar with the Java Collection Framework then you ve heard of java util Stack Please erase that idea from your mind completely or you ll be thoroughly confused here Bluetooth uses some terms like stack and profile which unfortunately are used in Java as well This chapter is all about Bluetooth so we ll clear up the confusion whenever there is a clash of terminology here You may notice that some of these layers are called protocols as well That s because these items are subprotocols of the Bluetooth protocol stack Others like TCP IP OBEX and WAP were not originated by the Bluetooth SIG but they have been incorporated into the Bluetooth protocol Those subprotocols are known as adopted protocols Host Controller Interface HCI The Host Controller Interface is alayer of software that passes all your data from your computer to your attached Bluetooth device For instance if you are trying to co
217. on return L2CAPConnection Connector open connectionuURL public static void main String args ClientApp client new ClientApp Running the Security Example Now let s see what happens when we run the example Figure 9 2 shows our security server waiting for a client to connect PROJECT TESTA 1 JZSE RANJIT 1 gt jave Serverfpp tinau avelink Bluetooth Server Application Figure 9 2 The security server is waiting for the client to connect Figure 9 3 shows the security client attempting to connect to the server C WINNT Syston omdvexe pria Chentp L JZSE RANJIT gt java Cltentapp Bluetooth Client Application OAddress 00863 Searching for Devices New Device discovered Searching for Service Figure 9 3 The security client is attempting to connect to the server The security server requires all clients to authenticate so the Atinav stack prompts the user to enter a PIN code as shown in Figure 9 4 Remote Device Address 131014370000 Enter Security Pin ox r i Oniro Center Figure 9 4 The security server prompts the user to enter a PIN for the application Note This of course is a part of Atinav s implementation of the BCC for their stack Other JSR 82 implementations may allow you to enter the PIN for your server prior to runtime Similarly the client is also prompted to enter a PIN Of course if the client enters an incorrect PIN then the authentication process wil
218. onfused with a Bluetooth profile Configurations typically encompass a broad classification of devices and profiles help to narrow the scope while providing more functionality to the configuration Figure 5 1 shows the J2ME world and the relationship between configurations and profiles Personal Profile PDA Profile Personal Basis Profile Mobile Information Device Profile Foundation Profile CLDC coc J2ME Figure 5 1 J2ME Profiles and configurations The Mobile Information Device Profile Now let s take a look at what is by far the most widely used J2ME Profile Mobile Information Device Profile MIDP If you have a Java enabled mobile phone then it s most likely a MIDP device As stated earlier the J2ME Profiles extend the functionality of a configuration The CLDC provides the following packages for the developer in order to create Java applications for small devices java lang basic core language classes java io networking classes java util utility classes javax microedition io more networking classes Note These are not the full J2SE versions of java lang java io and java util APIs The CLDC contains a subset of these packages that s optimized for micro devices The MIDP adds these additional packages for mobile devices javax microedition ledui user interface classes javax microedition midlet core MIDlet classes javax microedition rms data persistence classes
219. onment And that s it You now have a complete simulated JSR 82 application Figures 8 7 and 8 8 show the conversati between the client and the server Figure 8 7 The server has sent a message and the client responds Crvjewabluetoeth gt jeva ChatClient Mello fron server lle from client Figure 8 8 The client receives a message and sends a reply Summary This chapter gave you an introduction to the Rococo Impronto Simulator the first and only development environment that allows you to create JSR 82 compliant applications using simulated Bluetooth devices Bluetooth simulators are very useful tools in the application development process because they allow you to avoid configuring or debugging Bluetooth devices in your test environment InChapter 9 we re going to discuss the security measures that are provided by the Bluetooth specification and the JSR 82 in order to make your applications more secure Chapter 9 Bluetooth Security So far we ve discussed the benefits and the advantages of using Java and Bluetooth but we haven t addresser any detail the security implications of using this technology What prevents other people from using your Bluetc devices What prevents a hacker from intercepting your transmission if you re transmitting sensitive information financial personal or medical data In this chapter we ll take a look at the security measures built into the Blue specification and the JSR 82 APlin order to make your wi
220. opted by the Bluetooth SIG OBEX is pretty useful when you want to transfer objects like files between Bluetooth devices OBEX does not require that TCP and IP be present in the stack but the manufacturer is free to implement OBEX over TCP IP Note A Bluetooth vendor does not need to implement all the Bluetooth protocol layers into its product in order to be Bluetooth compliant For instance a Bluetooth cordless phone may very well only have HCI SDP L2CAP and TCS implemented into its stack That s perfectly fine because a cordless phone may not need any extra functionality Bluetooth Network Encapsulation Protocol BNEP The Bluetooth Network Encapsulation Protocol is a layer in the Bluetooth stack that allows other networking protocols to be transmitted over Bluetooth namely Ethernet A Bluetooth vendor has many options if it wants to implement TCP IP networking in its Bluetooth device BNEP is a popular choice because it encapsulates TCP IP packets in L2CAP packets before handing off the data to the L2CAP layer in the stack Human Interface Device Protocol HID The Human Interface Device Protocol is another adopted protocol in the Bluetooth specification It was originally defined in the USB specification and it lists the rules and guidelines for transmitting information to and from human interface devices like keyboards mice remote controls and video game controllers Table 2 3 is a handy guide that gives a brief description of the l
221. or in voice based applications and once again in this case you re better off using a native language such as C However this application may be feasible to do in Java if the Java Real Time Technology can be incorporated Distance Measuring The best wireless technology for accurately measuring distance is light waves and not radio signals Light waves are direct and the calculations can be pretty simple because the speed of light in various mediums is pretty well documented Using radio signals to measure distance can be quite tricky and one of the best ways to do that is to use triangulation like GPS transceivers do Whether you are using Java or C Bluetooth might be a viable technology for triangulation but definitely not for calculating or measuring accurate distances Note The key word here is accurate You can definitely use Bluetooth for proximity measurement ie where in the building is Bruce Hopkins In fact the Ericsson BlipNet does exactly that See Chapter 11 for more information on the Ericsson BlipNet So to put it succinctly you can only do what is possible using the constraints of the Bluetooth technology and what the JVM exposes to you If the JVM only gives you access to the RFCOMM layer for communication then you re stuck with it If the OBEX layer is not exposed to the JVM then don t expect to be able to send objects To increase application portability your Java Bluetooth vendor should implement the Java Bluetoot
222. orted Bluetooth Protocols The Palm DK supports the following Bluetooth protocols RFCOMM m L2CAP SDP OBEX System Requirements Here are the system requirements for the Palm DK Pentium based PC with at least 64MB of RAM Microsoft Windows 2000 service pack 1 or higher Minimum 35MB of free disk space JDK 1 3 1 PalmOS device with PalmOS 4 0 or higher Palm Bluetooth SDIO card or Sony Bluetooth Memory Stick Now developing ordinary stand alone Java applications on the PalmOS can be a little cumbersome because you need to create your application compile it build a PRC and deploy i e HotSync it on the PDA It gets even more cumbersome if you develop wireless Java applications because you ll need to create two applications client and server code and deploy to two PDAs Because of this it is highly recommended that you also get the following PalmOS emulator 3 5 with PalmOS 4 0 ROM or higher and Palm s Bluetooth stack TDK Bluetooth Palm Developers Kit includes TDK Bluetooth hardware This configuration is shown in Figure C 1 Figure C 1 With the TDK Bluetooth Developer s Kit and the PalmOS emulator you can develop deploy and test your Java Bluetooth applications all within the environment of your development machine Included Software The following items are included in the Impronto Developer Kit 1 0 for PalmOS IBM WebSphere Micro Environment for PalmOS the J9 KVM Apache ANT build tool m
223. overy and service discovery The Piconet Browser is a good utility program that you ll probably want to keep with you at all times If any concepts are unclear to you right now would be a good time to review them because in the next chapter we ll demonstrate communication by printing and we ll also take a look at the JPS API Chapter 6 Creating a Bluetooth Print Server with JPS API Highlights In the years to come many if not all printers will include a Bluetooth interface You ll be able to walk up to any printer download its drivers and print to it using the Hardcopy Cable Replacement Profile Unfortunately that s not the case today A large majority of the printers on the market today do not have a Bluetooth interface and in order to make them Bluetooth enabled you need to add a Bluetooth printer adapter like the one shown in Figure 6 1 Figure 6 1 You can use the 3Com Wireless Bluetooth Printer Adapter in order to make a traditional i e non Bluetooth printer Bluetooth enabled Let s say that you have a mobile Bluetooth device that is capable of printing for instance a laptop or PDA Whether you re a business user or a home user you most likely would want to print to the printers that you already have connected to your desktop computer If you re a consumer with one or two printers in your home then you may need to buy a few printer adapters for the printers that are not Bluetooth enabled which is somewhat practical
224. ow can you tell if your devices will interact properly and 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 on the PDA using the phone as a wireless modem That s why the Bluetooth SIG defined profiles A Bluetooth profile is a designed set of functionality for Bluetooth devices For instance using the examples just listed the phone and the PDA must both support the Synchronization Profile in order to synchronize data between themselves In order to send object data like a vcf file from the PDA to the phone both devices need to have the Object Push Profile implemented And finally the PDA and the wireless phone must both support the Dial Up Networking Profile in order for the PDA to wirelessly browse the Internet from the phone If you want your Bluetooth enabled devices to interact having a Bluetooth stack is not good enough Those devices also need to implement the same profile Now here s a list of many of the Bluetooth profiles and a description of what they do For most of them you can basically guess what they do the names are not cryptic Note For an exhaustive list of all the Bluetooth profiles go to the Bluetooth Member site at http www bluetooth org Generic Access Profile The Generic Access Profile is the most common Bluetooth profile All ot
225. owever that all the devices are physically connected by traditional TCP IP connections and the federation is not wireless unless the TCP IP network is WLAN There are no special precautions that need to be taken care of so this federation is formed in the usual manner Any of the devices in the federation can be Bluetooth enabled but it makes sense that either the Service Provider or the Service Consumer have Bluetooth capability so it can act as a bridge between the Jini federation and an outside Bluetooth piconet elsewhere A hybrid Bluetooth Jini federation is shown in Figure 12 9 Lookup Service N fi Service Consuser Service Provider h 8 Figure 12 9 In a hybrid Bluetooth Jini federation at least one of the devices participating in the federation must be Bluetooth enabled This federation is not necessarily wireless and the Jini Bluetooth enabled device acts as a bridge between the Jini federation and an external Bluetooth piconet A Jini Bluetooth Enabled Device The PsiNaptic PsiNode Dallas Semiconductor has a product line of sensors that can be connected to a two wire bus power and ground called 1 Wire They have a Java development platform and reference design called Tiny Internet Interface TINI that includes a 1 Wire interface PsiNaptic Inc has combined the TINI chipset with an Ericsson Bluetooth module in a reference design platform that they have named PsiNode The PsiNode platform is capable of acting
226. pendix contains all the fields and method signatures of the classes interfaces and exceptions that comprise the javax obex package of the JSR 82 API Interface Authenticator methods PasswordAuthentication onAuthenticationChallenge java lang String description boolean isUserIdRequired boolean isFullAccess byte onAuthenticationResponse byte userName Interface ClientSession methods HeaderSet connect HeaderSet headers HeaderSet HeaderSet HeaderSet Operation long getCo crea dele teHeaderSet te HeaderSet headers disconnect HeaderSet headers get nnec Operation put void setAuthen void setCo nnec HeaderSet headers tionID HeaderSet headers ticator Authenticator auth tionID long id HeaderSet setPath HeaderSet headers boolean backup boolean create Interface HeaderSet fields static int APPLICATION PARAMETER static int COUNT static int DESCRIPTION static int HTTP static int LENGTH static int NAME static int OBJECT CLASS static int TARGET static int TIME 4 BYTE static int TIME ISO 8601 static int TYPE static int WHO methods void createAuthenticationChallenge java lang String realm boolean userID boolean access java lang Object getHeader int headerID int getHeaderList int getResponseCode void setHeader int headerID java lang Object headerValue Interface Oper
227. phone entries so Aunt Clarissa Johnson becomes Ant Clrssa Jnsn If you own a PDA then you probably agree that PDAs are also useful devices They can store thousands of contact entries and they are a lot better for entering data compared to mobile phones Since you can t store your entire contact list on your mobile phone you probably have it stored on your PDA Unfortunately it s a little inconvenient to look up a phone number on the PDA and then manually dial the number on the mobile phone With a Bluetooth enabled PDA and a Bluetooth enabled mobile phone you can keep your entire contact list on the PDA where it s far more convenient Don t even bother to store phone numbers on your phone Whenever you are ready to dial a number you just look up the number on the PDA and send the phone number over to the phone no wires no hassle Figure 1 1 is a picture of one of HP s advanced Bluetooth enabled PDAs PC O Figure 1 1 The short antennae on HP iPAQ 5400 series Pocket PC allows it to communicate via Bluetooth and 802 1 1b For added security this model also includes a fingerprint reader Connection Sharing Laptop to Phone lf you re a programmer and you have a laptop you know how cumbersome it is to get a dial up Internet connection on your mobile phone You may have an Internet ready phone but you may not have the right cable Maybe you have the right cable which isn t cheap but you need additional software to esta
228. ple headsets be able to connect to your phone while you are using it On the other hand a multipoint device is able to communicate with up to seven other devices at the same time Figure 2 5 is a diagram of a multipoint device communicating to other devices within range using Bluetooth technology Figure 2 5 You can connect to up to seven Bluetooth devices at a time if you have multipoint capable hardware Bluetooth Device Power Classes Bluetooth hardware devices are broken up into three power classes Table 2 2 describes the device classes and their capabilities Table 2 2 Bluetooth Device Power Classes CLASS POWER RATING RANGE Class 1 100 mW 100 meters Class 2 2 5 mW 20 meters Class 3 1 mW 10 meters So as we stated in Chapter 1 Bluetooth devices are not limited to 10 meters in range CROSS See Bluetooth vs 802 11b in Chapter 1 for details on the initial discussion of REFERENCE Bluetooth s range How can you determine a Bluetooth device s power class and thereby know its range The power class is rarely printed on the unit so here s a hint if you re trying to distinguish the power class of a device that you ve never seen before If that device is powered by batteries or if it fits in your hand like a wireless phone or a headset then it is most likely a Class 2 or 3 device If the Bluetooth device is built right into the hardware of another unit and that unit is plugged into AC power then it i
229. print service 101 JPS API packages 99 JPS application example JPSPrint 102 104 JPSBluetoothPrintClient java listing 109 112 JPSBluetoothPrint java listing 105 109 JPSPrint application 102 104 JPSPrint java listing 102 104 JSR 82 API 35 42 45 73 application simulation 152 as only standardized Bluetooth API 39 40 benefits of 38 40 compatible code 96 independent of stack and radio 38 39 OBEX APIs in 121 136 role of 35 36 JSR 82 compliant Bluetooth applications 139 JSR 82 compliant Bluetooth stack layers 39 JSR 82 Expert Group companies in 35 36 JSR 82 OBEX API file transfer example 127 136 JSTARTUP INI file 188 190 JVM Java Virtual Machine 186 JVM for Micro BlueT arget 186 187 Index K Keyboard Bluetooth services 60 Index L L2CAP Logical Link Control and Adaptation Protocol 20 client connections 71 connection authentication and authorization 163 connections 70 72 163 vs RFCOMM 72 server connections 70 L2CAP layers 70 L2CAPConnection interface 262 L2CAPConnection methods 71 72 L2CAPConnection object 71 72 L2CAPConnectionNotifier interface 262 L2CAPEcho Service example 192 207 L2CAPEchoClient java listing 196 207 L2CAPEchoServer java listing 193 196 LAN Access Profile 26 232 Laptop to phone connection sharing 5 Layers Bluetooth protocol UUID values for 61 Layers of the protocol stack 18 20 23 61 Leasing service Jini 244 Light waves 34 Line of sit
230. protocol 22 High level API MIDP 79 Home Bluetooth in 8 Home office Bluetooth in 6 Host Bluetooth 41 Host Controller Interface 41 Hotel business center Bluetooth enabled 156 Hotel e mail stations 229 HP iPAQ 5400 series Pocket PC antennae 4 HTTP protocol stack 17 Human Interface Device Profile 28 Human Interface Device HID protocol 22 Hybrid Bluetooth Jini federation 253 255 HYFLASH utility HyNetOS 189 HYLOAD utility HyNetOS 189 HYMON utility HyNetOS 189 190 HyNetOS for Micro BlueTarget 185 191 Bluetooth implementation 186 187 operating environment components 185 protocol manager 187 structural overview 186 tools 189 1 90 Hyperstone AG microprocessor 183 Hyperstone RISC DSP CPU architecture 185 HYTRACE utility HyNetOS 190 Index l V O performing with the GCF 80 Import statement 95 Im pronto Developer Kit 1 0 for PalmOS 269 272 Impronto Simulator Rococo 139 152 Console 141 143 device list 151 features of 139 installation of 140 141 running an application in 144 v 1 1 installation screen 140 Infrared vs Bluetooth 1 InitBlipServerConnection constructor 234 InputStream 131 193 Intercomm Profile 27 Interoperability any device to any device 6 IrDA Infrared Data Association 21 115 IsAuthenticated method of Remote Device 157 IsEncrypted method of RemoteDevice class 162 IsTrustedDevice method of RemoteDevice class 158 Index J
231. pt to authenticate the If the authenticate parameter is not in the URL string at all then the implementation treats it as false Lt you set encrypt Of authorize tO true Client Authentication Bluetooth clients can also require the server to authenticate by setting the authenticate parameter to true shown here String url btspp 02AB45AC35DF 00112233445566778899AABBCCDDEEFF authenticate If the authenticate parameter is set to false or is not in the URL at all then the client will not require the to authenticate Note Why would the client request the server to authenticate it especially if the server didn t require authentication Well since authentication is a requirement for encryption the client may want to be authenticated to the server in order to send some data securely even though the server doesn t requi Whether you re a client or a server you can request authentication even after the connection is established as here get an instance of the RemoteDevice if we don t already have it assume that we have an active Connection object named conn RemoteDevice remoteDevice RemoteDevice getRemoteDevice conn remoteDevice authenticate The JSR 82 API also gives you a method to check to see if your Connection to a RemoteDevice is authenti Just call the isAuthenticated method of RemoteDevice Note Have you noticed that in both client and server authentication the PIN is never specified in
232. r Constructors BlipServerConnectionException java lang String s java lang Throwable e Class BlipServerEventAdapter public abstract class BlipServerEventAdapter extends java lang Object implements BlipServerEventListener An abstract adapter class for receiving events from the BlipServer The methods in this class are empty The class exists as convenience for creating listener objects which only listens to a certain class of events package com ericsson blipnet api event Constructors BlipServerEventAdapter Methods void handleBlipNodeEvent BlipNodeEvent e Called by the BlipServer event dispatcher when a BlipNodeEvent occurs void handleConnectionEvent ConnectionEvent e Called by the BlipServer event dispatcher when a ConnectionEvent occurs void handleObexEvent ObexEvent Called by the BlipServer event dispatcher when an ObexEvent occurs Class BlipServerEventFilter public final class BlipServerEventFilter extends java lang Object implements java io Serializable This class is used to filter notification of events for client applications which implement BlipServerEventListener Package com ericsson blipnet api event Constructors BlipServerEventFilter int eventClasses int eventIDs BluetoothAddress blipNodeIDs BluetoothAddress terminalIDs Constructs a BlipServerEventFilter Methods boolean contains Event even
233. r as well only downside is that the simulator will create generic dummy devices Chat Example The chat example we present here uses the Serial Port Profile to send text messages from one simulated Blue device to another In Chat Server java the chat server registers its service and waits for a client to connect a client connects the server prints the client s message to the command line and prompts the server to respon ChatClient java the client searches for the server and creates a Serial Port Profile connection after obtain the connection URL Listing 8 2 shows the code for Chat Server java and Listing 8 3 shows the code for ChatClient java Listing 8 2 ChatServer java import java io import javax bluetooth import com rococosoft io class Server StreamConnection con null StreamConnectionNotifier service null InputStream ip null OutputStream op null String serviceURL btspp localhost 1111 name ChatServer public Server throws IOException f Extends a stream for client to connect service StreamConnectionNotifier Connector open serviceURL Server waiting for client to connect con service acceptAndOpen Open streams for two way communication ip con openInputStream op con openOutputStream Starts a new thread for reading data from inputstream while the present thread goes forward and write data to outputstream thus enabling a two way communic
234. r versions to try to compete with 802 11 speeds but you might see data rates of 4 8 or even 12 Mb s Bluetooth s niche is as a low power wireless communication protocol so don t expect Bluetooth 2 0 to be a power hog CROSS SeeChapter 1 for a discussion of Bluetooth versus 802 11b REFERENCE This chapter is all about Bluetooth We ll give you brief history on how it began and how it got its name Next we ll show you the radio spectrum and where Bluetooth fits in with devices that you probably already know about Afterwards we ll describe the anatomy of a Bluetooth enabled device by giving a description of Bluetooth hardware the Bluetooth stack and Bluetooth profiles For the remainder of this book when we refer to Bluetooth we are referring to the 1 1 version of the spec Now let s dig into Bluetooth A Brief History of Bluetooth Bluetooth got its name from King Harald Bl tand Bluetooth of Denmark His most notable accomplishment was that he united Denmark and Norway under Christianity in the 10th century In 1994 Ericsson conducted the first research studies of a wireless technology to link mobile phones and accessories Years later in 1997 Ericsson formed the Bluetooth Special Interest Group Bluetooth SIG so that other companies could use and promote the technology At that time the Bluetooth SIG consisted of the following promoter companies Ericsson a IBM Intel a Nokia Toshiba Later on in 1999 after the 1 0 specif
235. rPhone MEI Figure 5 3 The application starts and is now looking for remote Bluetooth devices Once it finds another device it goes into nondiscoverable mode as shown in Figure 5 4 DefaultColorPhone PIE B oc 10 14 37 60 00 D o ED oma Figure 5 4 After a remote device is found we now go into stealth mode i e nondiscoverable In this example we re using the J2ME Wireless Toolkit configured with the Atinav Bluetooth SDK The Bluetooth device that we re using is a TDK USB module as shown in Figure 5 5 el J Figure 5 5 The TDK USB Bluetooth device using a CSR Bluetooth radio The code for this example is shown in Listings 5 1 and 5 2 Listing 5 1 Stealth java import javax microedition midlet import javax microedition lcdui import javax bluetooth import java io import java util import javax microedition io import com atinav bcc The Timer and the BeamTsk class is used to create the beam of 3 concentric circles blinking It has no purpose except visual enhancement wre public class Stealth extends MIDlet private Display display private GUI canvas private Timer tm private BeamTsk tsk private String dev private RemoteDevice devicel public Stealth display Display getDisplay this canvas new GUI this tm new Timer tsk new BeamTsk canvas tm schedule tsk 1000 1000 protected void startApp display setCurrent c
236. rSets to instruct the OBEX server what we want to do The CONNECT Operation The first OBEX operation that needs to be created and sent to the OBEX server is CONNECT This is accomplished by the following con ClientSession Connector open serviceURL hdr con connect hdr Theconnect method of this ClientSession instance returns a HeaderSet object where we can inspect and determine if our CONNECT operation was a success The GET Operation Now that we have successfully performed our CONNECT operation we are able to create other operations like GET PUT and SETPATH The code that you would use in order to create and send a GET operation to an OBE server looks like this hdr con createHeaderSet hdr setHeader HeaderSet TYPE text plain hdr setHeader HeaderSet NAME Hello txt Operation op con get hdr If the operation was successful then just open up an InputStream and read the data InputStream in op openInputStream Now that you have an InputStream in hand you can save your file to disk The DISCONNECT Operation Creating and sending a DISCONNECT operation is pretty simple All you need to do is call the disconnect method of the ClientSession object clientSession disconnect null The full code for FT Client is show in Listing 7 2 Listing 7 2 FTClient java import java io import java util import javax microedition io import javax bluetoo
237. register itself to the BlipNet Figure 11 3 is a picture of a single BlipNode unit Figure 11 3 A single BlipNode BlipManager Application The BlipManager tool is used to configure and administer the BlipNet system As shown in Figure 11 4 the BlipManager gives you a visual representation of all the BlipNodes on your network Figure 11 4 The BlipManager application Out of the box the BlipManager comes with the following features Device filtering Security administration Node administration With the device filtering feature you can block certain Bluetooth devices from using the BlipNet You can create this filter based upon the client device s address or the device s class i e laptop cell phone headset or based upon the available services on the device The security administration feature allows you to assign PINs for individual nodes or for the entire BlipNet Using the node administration features of the BlipManager you can administer an individual node or create a group of nodes and administer them collectively The node administration features also give you the ability to activate and deactivate the profiles on your nodes Using this feature it is very easy to configure multiple enterprise Bluetooth applications on the same BlipNet network For instance in a grade school environment all the BlipNodes at the entrance of the school can be configured to use only the Object Push Profile so that parents and visitors are gr
238. release Releases the BlipNodeHandle for use by other applications void removeFromBlipNodeDenyList BluetoothAddress terminalID Removes the specified device from the local deny list on this BlipNode void removeSession BluetoothAddress terminalID Session sessionType Removes the specified session from this BlipNode if the session exists void setBlipNodeDenyList BluetoothAddress terminalIDs Sets the local deny list on this BlipNode to the specified list void setBusinessCard java lang String businessCard Configures the business card of this BlipNode Class BlipNodeHandleinUseException public final class BlipNodeHandleInUseException extends BlipServerException Thrown by BlipServerConnection when an application attempts to get a handle for a BlipNode which is already used by another application Package com ericsson blipnet api blipnode Constructors BlipNodeHandleInUseException BlipNodeHandleInUseException java lang String s BlipNodeHandleInUseException java lang String s java lang Throwable e Class BlipNodeHandleReleasedException public final class BlipNodeHandleReleasedException extends BlipServerException Thrown by BlipNodeHandle when an application attempts to execute a method on a released BlipNodeHandle The handle may have been released either by the application itself or by the server due to a reboot of the Blip Node Package com
239. reless applications more secure We ll wrap things ug demonstration of how to use the Mobiwave Bluetooth Protocol Analyzer in order to see what s in the air when transmitting data between Bluetooth devices Bluetooth Security Measures Data security is an important aspect of any networked application All data that is in transit is vulnerable to an al from an eavesdropper it doesn t matter if the connections are physical or wireless Developers must realize th is no way to completely ensure that information transmitted wirelessly will only reach the intended destination Note Well except for infrared but of course you already knew that For application developers the Bluetooth specification addresses security in three ways authentication authori and encryption Let s look at these in more detail Authentication Authentication with Bluetooth consists of a simple challenge response mechanism The Bluetooth specification not provide any means to authenticate users you can only authenticate devices So the challenge response dc involve a user name and password as typical authentication schemes Authentication with Bluetooth only involv personal identification number PIN During the authentication process the PIN code is never transmitted from the client to the server In order to authenticate the client creates a 128 bit shared link key which is derived from the PIN If the PIN codes on the and the server do not match then the auth
240. reless phones and personal devices Bluetooth for Java is not an overview of Bluetooth In the book Bruce Hopkins and Ranjith Antony describe how to develop wireless Java applications using Bluetooth for a variety of platforms This includes an API overview of the Java library development of Bluetooth based services highlights of security concerns and walkthroughs for development with some of the different tools available Programs will not be just J2ME micro devices based but will also be for J 2SE client desktop About the Authors Bruce Hopkins is an early adopter of Java technology and has used it in a wide variety of applications ranging from embedded systems to enterpise applications He currently works as a technical architect at Redwood Solutions an IT services firm in Livonia Michigan Ranjith Antony is the technical lead for Atinav an early Bluetooth provider adopter Bluetooth for Java BRUCE HOPKINS AND RANJITH ANTONY a Apress Copyright 2003 by Bruce Hopkins and Ranjith Antony All rights reserved No part of this work may be reproduced or transmitted in any form or by any means electronic or mechanical including photocopying recording or by any information storage or retrieval system without the prior written permission of the copyright owner and the publisher ISBN pbk 1 59059 078 3 Printed and bound in the United States of America 12345678910 Trademarked names may appear in this book Rather
241. rget standard version and Figure 10 2 shows the Micro BlueT arget Starter Kit Figure 10 1 The Micro BlueT arget standard version is asmall form factor embedded system with a board outline of just 3 25 9 cm This is a great solution for OEMs that want to make their devices Bluetooth enabled Figure 10 2 The Micro BlueT arget Starter Kit uses a standard Micro BlueTarget and adds RS 232 and Ethernet ports which is ideal for developers who need to create quick prototypes and proofs of concepts The Micro BlueT arget has been designed to meet typical requirements of fixed wireless infrastructure components What s a fixed wireless device A fixed wireless system is typically a large stationary device that is capable of wireless communication Consumer oriented fixed wireless systems are things like network access points information kiosks and vending machines see Figure 10 3 On the other hand a typical example of a fixed wireless system for commercial use would be a large machine in a manufacturing center see Figure 10 4 U u Figure 10 3 A Bluetooth phone utilizing the services of a fixed wireless consumer system a Bluetooth enabled vending machine Figure 10 4 A Bluetooth PDA receiving the status from a fixed wireless commercial system a Bluetooth enabled machine in a manufacturing facility In the rest of this chapter we ll take a look at the physical aspects of Micro BlueTarget starting off with its hardware co
242. rint event Documents By far the most important piece of data that will be exchanged between the client and the printer is the document itself In JPS terminology the term document is used in a generic sense it only refers to the item to be printed A document could be an image a style sheet an actual text document or anything that s printable The classes that will enable you to create a document are included in the javax print package This package also has functionality that will allow you to create documents of well known data formats such as HTML PostScript GIF and JPEG Attributes Of course you ll have to do more than just give the printer adocument you also need to tell the printer what exactly needs to be done to the document Print attributes will indicate to the printer things such as the size of the paper required how many copies to print the number of pages and duplexing The packages javax print attribute and javax print attribute standard allow you to create these attributes Events The JPS event model is pretty simple after you ve submitted a print job to the printer the printer will inform you of its status through events You can be notified of things like the printer s on off status the number of pages printed and so on The javax print event package deals with creating and handling these events A Step by Step JPS Application Lets walk through a simple JPS application Along the way we ll identify major
243. rmine if this is the last packet to send or if there will be additional packets if data length index lt MaxOutBufSize temp new byte data length index System arraycopy data index temp 0 data length index else temp new byte MaxOutBufSize System arraycopy data index temp 0 MaxOutBufSize con send temp index MaxOutBufSize Prepare a receive buffer int rxlen con getReceiveMTU byte rxdata new byte rxlen Wait to receive the server s reply method blocks rxlen con receive rxdata Here we ve got it String message new String rxdata 0 rxlen System out printin Server replied message Close the connection to the server con close catch BluetoothConnectionException e System out printin Failed to send the message System out printin BluetoothConnectionException e getMessage System out printin Status e getStatus catch IOException e System out printin Failed to send the message System out printin IOException e getMessage return false return true Wireless System Monitor Example In the Wireless System Monitor example we re going to look at an industrial device that is in great need of wirel communication the Programmable Logic Controller PLC PLCs are industrial control devices that programm control large machinery They ar
244. rofile allows you to use a Bluetooth enabled handset to connect to a Bluetooth enabled landline phone to place calls For instance through this profile you continue to receive calls to your home phone but you have the convenience of answering that call on your Bluetooth wireless phone without using the minutes of the calling plan of your wireless phone Intercom Profile If two Bluetooth enabled devices are within range and they support the Intercom Profile then they can function just like regular intercoms Generic Object Exchange Profile The Generic Object Exchange Profile is the generic profile that all profiles use if they want to employ the functionality of the OBEX protocol in the Bluetooth stack Object Push Profile The Object Push Profile provides the functionality for a device to push and pull an object Using this profile though you are limited to acertain class of objects like vCards File Transfer Profile The File Transfer Profile is a more robust profile for transferring objects You can use the File Transfer Profile to transfer files and folders from one Bluetooth enabled device to another Synchronization Profile You use the Synchronization Profile to synchronize data between two Bluetooth enabled devices The most common applications for this profile would be to synchronize data between a PDA and a PC Basic Printing Profile The Basic Printing Profile allows a Bluetooth enabled device to send plain text to
245. ronized this this notify break This function notifies the Thread waiting in main if a service search is terminated ie ig the responsecode is SERVICE_SEARCH_COMPLETED or SERVICE_SEARCH_NO_RECORDS public synchronized void serviceSearchCompleted int transID int respCode if respCode SERVICE_SEARCH_ERROR System out printin nSERVICE_SEARCH_ERROR n en ve lt H Q n if respCode S EARCH COMPLETED System out printin nSERVICE_SEARCH_COMPLETED n if respCode SERVICE_SEARCH_TERMINAT D System out println n SERVICE_S ARCH_TERMINATED n E T if respCode SERVICE SEARCH NO RECORDS synchronized this this notify System out printin n SERVICE_SEARCH_NO_RECORDS n if respCode SERVICE_SEARCH_DEVICE_NOT_REACHABLE System out println n SERVICE SEARCH DEVICE NOT REACHABLE n Once the device inquiry is completed it notifies the Thread that waits in the Main public synchronized void inquiryCompleted int discType this notify Opens the connection to the Server L2CAPConnection getconnection throws IOExcepti
246. rst device is discovered R BCC setDiscoverable DiscoveryAgent NOT_DISCOVERABLE canceliInquiry discoveryAgent public void inquiryCompleted int discType cancel true this notify paint public void paint Graphics g if i 0 Used to clear the portion of the screen g setColor 255 255 255 g fillRect 25 10 50 70 else draw the image of phone at given coordinates at the top left of the screen g drawImage img 10 30 Graphics LEFT Graphics TOP draw a string at the bottom left g drawString Me 10 45 img getHeight Graphics LEFT Graphics BOTTOM if cancel draw an arc at given coordinates g drawArc x y wd ht 270 180 else g drawImage img 90 30 Graphics RIGHT Graphics TOP g drawString I am in Stealth Mode 2 100 Graphics LEFT Graphics BOTTOM try img Image createImage phonegray png catch Exception e e printStackTrace g drawImage img 10 30 Graphics LEFT Graphics TOP midlet exitTimer public void commandAction Command c Displayable s if c exitCommand midlet exitStealth Listing 5 2 BeamTsk java import java util public class BeamTsk extends TimerTask private GUI canvas Creates a new instance of BeamTsk public BeamTsk GUI canvas this canvas canvas public void run if canvas count gt 5 canvas cancel true if
247. s catch BluetoothStateException e Failed to start the search on this device try another device System out printin BluetoothStateException e getMessage Determine if another search can be started If not wait for a service search to end synchronized this serviceSearchCount System out printin maxServiceSearches maxServiceSearches System out printin serviceSearchCount serviceSearchCount if serviceSearchCount maxServiceSearches System out printin Waiting try this wait catch Exception e System out printin Done Waiting serviceSearchCount Wait until all the service searches have completed while serviceSearchCount gt 0 synchronized this try this wait catch Exception e if record null System out printin Record is not null return true else System out printin Record is null return false Finds the first echo server that is available to send messages to public ServiceRecord findEchoServer If there are any devices that have been found by a recent inquiry we don t need to spend the time to complete an inquiry RemoteDevice devList agent retrieveDevices DiscoveryAgent CACHED if devList null if searchServices devList return record Did not find any echo serv
248. s m CONNECT Em DISCONNECT m PUT E GE m SETPATH E ABORT m CREATE EMPTY Em PUT DELETE OBEX servers in turn return responses back to the OBEX clients such as the following E SUCCESS E FAILURE m CONTINUE Note There are a lot more OBEX responses than just these three All the valid response codes in the javax obex API are contained in the javax obex ResponseCodes class whichis described later in this chapter Figure 7 3 is an illustration of the message flow that takes place during a simple OBEX session OBEX Client Application OBEX Server Application Connect Request Success Figure 7 3 A sample message flow between OBEX clients and servers The client initiates the communication process by sending a request packet with the CONNECT operation The request packet contains the code for the operation the length of the packet itself and the headers Upon receiving the request the server responds with a response packet that contains the response code the response length and some response data Under normal circumstances the server returns a packet with a response code of SUCCESS If however some problem has occurred then the server returns a FAILURE code ThePUT operation allows the client to send an object to the server It s possible that a small object may fit into a single PUT request packet If not then the client sends multiple pack
249. s how to create a document from a GIF file DocFlavor flavor DocFlavor INPUT_STREAM GIF FileInputStream fiInput new FileInputStream nicePic gif Doc doc new SimpleDoc fInput flavor null Searching for a Print Service Now it s time to find a suitable printer for your needs In the JPS you ll never interact directly with a printer you will always have to interact with a print service that represents that printer So when you are searching for a printer either connected peripherally to your computer or somewhere on your network you are searching for print services The code that follows shows you how to search for a print service that can print GIF files In addition this example also demonstrates how to specify some print attributes this print service is capable of printing two copies double sided on A4 size paper DocF lavor flavor DocFlavor INPUT_STREAM GIF PrintRequestAttributeSet attribSet new HashPrintRequestAttributeSet attribSet add new Copies 2 attribSet add MediaSizeName ISO A4 attribSet add Sides TWO SIDED LONG EDGE PrintService services PrintServiceLookup lookupPrintServices flavor attribSet As you can see the static method LookupPrintServices from the class javax print PrintServiceLookup returns an array of PrintService objects EachPrintService represents a printer that is capable of printing according to the attributes that you specified Cr
250. s illustrated in Figure 5 2 Byte Array Byte Array Byte Array Figure 5 2 A logical representation of an RMS record store The main class in the RMS is javax microedition rms RecordStore This class contains the methods for creating updating deleting and querying a record store A few interfaces are also provided is this package and they help you whenever you need to enumerate compare and filter the data stored inside the record store The RMS also includes a listener interface called javax microedition rms RecordListener When you associate this listener with a record store the interface reports events that correspond to inserts updates and deletes of data that are in the record store Performing I O with the GCF In order for J2ME applications to perform any networking or I O they must use the java io and javax microedition io packages These packages together form the Generic Connection Framework GFC The general philosophy behind the GCF is to create a framework to abstract the communication process through a single class called Connector You can then use Connector to create any connection like file VO streams TCP IP socket connections HTTP connections etc In order to open a connection just use theopen method Connector open protocol address parameters lf a user wants to open an HTTP connection the connection URL will look like this Connector open http mydomain com Working with the Example Cod
251. s most likely a Class 1 device Don t worry about Bluetooth device classes too much just be aware that Bluetooth can communicate at greater distances than 10 meters The Bluetooth Protocol Stack Your computer is a pretty powerful device It has a processor memory bus hard drive and other neat things The unfortunate thing is that the computer doesn t have the ability to use peripherals by itself Common peripherals like CD DVD drives graphic displays mice keyboards modems printers and scanners all need drivers Your computer needs a driver to instruct it how to use a peripheral By itself the computer has no idea how to print to a printer or scan with a scanner The computer is pretty powerful but also pretty helpless The device driver is the controlling agent that helps the computer to communicate with its peripherals The Bluetooth stack and Bluetooth hardware have a similar relationship The Bluetooth stack is a controlling agent it could be software firmware hardware or a combination of all three that implements the Bluetooth protocol and also allows you to control your Bluetooth device programmatically The Bluetooth stack allows you to do these two things Communicate with other Bluetooth devices Control your own Bluetooth device So if you re familiar with the HTTP protocol stack and how it works then you can relate to the Bluetooth protocol stack A Web browser uses an HTTP protocol stack so that it can receive Web
252. sce id testProperties iTransport null row new Error No connection to Host Controller defined tInt bluetooth security mode lt NON SECURE MODE 1 i gt LINK LEVEL MODE 3 row new Error bluetooth security mode must be NON SECURE MODE 1 SERVICE LEVEL MODE 2 or LINK LEVEL MODE 3 EInt bluetooth 1l2cap receiveMTU max lt 48 throw new Error bluetooth l2cap receiveMTU max must be at least 48 bytes default value is 672 private int getInt String prop return Integer parseInt String ht get prop So as we stated earlier stack initialization must occur before you can do any real work in your Bluetooth application whether you invoke it directly in your code or not Device Management LocalDevice RemoteDevice and DeviceClass are the classes in the Java Bluetooth specification that form the Generic Access Profile and allow you to perform device management These classes allow you to que some statistical information about your own Bluetooth device LocalDevice and also some information on th devices in the area RemoteDevice The DeviceClass object gives you information about the official class device CoD as defined in the Bluetooth specification javax bluetooth LocalDevice There is a famous quote that says Know thyself Well this class allows you to do exactly that The LocalDevice class is the class that gives you information about yourself the local Bluetooth devic
253. shObject Class ObexServerHostedFile public final class ObexServerHostedFil xtends java lang Object implements ObexPushObject AnObexServerHostedFile is an OBEX push object which will be read from the server s local storage when the object is pushed to a terminal The advantage of a server hosted file compared to a regular ObexFile is that the contents of the file are not transferred across the network when pushing the file This may be desirable when pushing very large objects Package com ericsson blipnet api obex pushobjects Constructors ObexServerHostedFile java io File file ObexServerHostedFile java io File file java lang String obexType Methods boolean fileExists java io File getFileDescriptor byte getObexBody Returns the body of this ObexPushObject java lang String getObexName Returns the name of this ObexPushObject java lang String getObexType Returns the mime type of this ObexPushObject Interface PageData public interface PageData extends java io Serializable APageData object contains all data needed to do a link establishment after an inquiry Using the data in this object link establishment time will be shortened Used when BlipNode is in INQUIRY RESULT mode and the application does the link establishment via the BlipServer API Package com ericsson blipnet api bluetooth Interface RemoteBlipServerEventListener public interface RemoteBlipSer
254. so provide an object that will implement the DiscoveryListener interface in order to receive event callbacks when services that match your UUID criteria are discovered This method returns an int that is the transaction ID You can later use the transaction ID to cancel this search if you need to public String selectService UUID uuid int security boolean master This method also allows you to search for services but it has a slight twist that makes it different from searchServices This method accepts neither a DiscoveryListener nor a RemoteDevice object Bi using this method you can perform a search for a particular UUID that is available on ANY device in the area there is a match then this method returns a St ring that will be used in the Connector open method in order to establish a connection to that device Be sure to notice that this method only allows you to search on a singleUUID and not multiple UUIDs as in searchServices Unfortunately there is no method available in the JSR 82 specification that will allow you to discover every service offered by remote devices By using either searchServices of selectService you need to know the UUID of the service that you re looking for before you attempt to perform a search Note You may be able to discover every service on a remote device if that device has all of its services categorized with a BrowseGroupList attribute in the service record If not then you re out of luck See
255. specified PrintService pservices PrintServiceLookup lookupPrintServices flavor attribSet if pservices length gt 0 DocPrintJob job pservices 0 createPrintJob Adding a PrintStatus Listener job addPrintJobListener status Create a Doc implementation to pass the print data FileInputStream fInput new FileInputStream fileName Doc doc new SimpleDoc fInput flavor null Print the doc as specified try job print doc attribSet catch PrintException e System err printlin e else System err println No suitable printers return true public void connectToClientAndPrint throws Exception System out println Host Device LocalDevice getLocalDevice getBluetoothAddress String url btl2cap localhost uuid name simplePrintServer UUID uuid new UUID 6666 true L2CAPConnectionNotifier l2capNotifier L2CAPConnectionNotifier Connector open url 1l2capConn l2capNotifier acceptAndOpen maxRecv 1l2capConn getReceiveMTU System out printin Connected to a client Receive buffer Size is maxRecv new Thread this start public void run try packet receive byte data new byte maxRecv Reading fileName blocks assuming fileName always less than 48 bytes int dataSize 12capConn receive data byte fileNameAsBytes new byte dataSize System arraycopy data 0 fileNameAsBytes
256. ss Note There is no such thing as client authorization Why Well since authorization is not a requirement for encryption it doesn t make sense for a client to request a server to authorize tt if the server does not it A good use of the authorization security measure occurs when you re dealing with personal devices For instan you have a Bluetooth enabled TV and a Bluetooth enabled remote control then you want your TV to only obey commands coming from your remote obviously Otherwise you ll be vulnerable to common pranksters coming range of your house and changing your channels while you re watching TV or even worse turning on your T high volume at 3 00 a m Encryption Authentication and authorization are good if you want to prevent unwanted users from accessing the services o Bluetooth devices However neither of those security measures will protect your sensitive data from a hacker w the right tools to sniff your data while it s being transmitted Encryption however is the security measure that y employ in order to protect your sensitive data transmissions Now in order to encrypt information whether you re using Bluetooth or not you need an encryption algorithm encryption key and the information that you want to protect An encryption algorithm also called a cipher is sir procedure that is followed in order to scramble the data Some well know encryption algorithms are Blowfish T RC4 DES TripleDES IDEA CAST and Ri
257. ss of Device Major type as a text description java lang String getMinorTypeText Returns the Class of Device Minor type as a text description int hashCode Returns a hashCode for this Class Of Device boolean isAudioSet Examines the Audio bit of the Class Of Device boolean isCapturingSet Examines the Capturing bit of the Class Of Device boolean isInformationSet Examines the Information bit of the Class Of Device boolean isLimitedDiscoverableSet Examines the Limited Discoverable bit of the Class Of Device boolean isNetworkingSet Examines the Networking bit of the Class Of Device boolean isObjectTransferSet Examines the Object Transfer bit of the Class Of Device boolean isPositioningSet Examines the Positioning bit of the Class Of Device boolean isRenderingSet Examines the Rendering bit of the Class Of Device boolean isTelephonySet Examines the Telephony bit of the Class Of Device java lang String toString Returns a String representation of this Class Of Device Interface ConnectionEvent public interface ConnectionEvent extends Event An event indicating that a connection related action has occurred in the server Package com ericsson blipnet api event Methods boolean equals java lang Object obj Returns true if content of object is equal to this int getCause Returns the cause of this event int getSessionType R
258. sses in more detail javax obex ClientSession TheclientSession interface is a subclass of the javax microedition io Connection class and represents an OBEX connection from the client s point of view You can obtain an instance of this interface by using the following line of code ClientSession session ClientSession Connector open connectURL This interface provides a way to define headers for OBEX operations For instance the methods put andget respectively allow you to create PUT and GET operations Those methods returna javax obex Operation object so that you can complete the operation Note See the description of javax obex Operation later inthis section for more information on how to complete GET and PUT operations The methods connect disconnect and setPath complete their respective operations CONNECT DISCONNECT and SETPATH and return the result in a javax obex HeaderSet object javax obex HeaderSet TheHeaderSet interface can be used to define all OBEX headers even custom headers It can be instantiated by calling ClientSession createHeaderSet An example of an OBEX client setting theNAME and TYPE headers is shown here HeaderSet hdr clientSession createHeaderSet Creating a header set to request Hello txt file from the server hdr setHeader HeaderSet TYPE text vCard hdr setHeader HeaderSet NAME Hello txt An OBEX server in turn can retrieve the
259. star System out printin BluetoothState Exception Find an Echo Server in the local area ServiceRecord echoService client find EchoServer EchoClient lt message gt t Bluetooth System e getMessage i if echoServic null retrieve the connection URL string String conURL choService getConnectionURL ServiceRecord NOAUTHENTICAT T _NOENCRYPT create a new client instance EchoClient echoClient new EchoClient conURL and send the message give on the command line echoClient sendMessage args 0 else System out printin No Echo Server was found Called when a device was found during an inquiry An inquiry searches for devices that are discoverable The same device may be returned multiple times public void deviceDiscovered RemoteDevice btDevice DeviceClass cod System out printin Found device btDevice getBluetoothAddress deviceList addElement btDevice The following method is called when a service search is completed or was terminated because of an error Legal values include SERVICE SEARCH COMPLETED SERVICE SEARCH TERMINATED S SERVICE SEARCH ERROR SERVICE_SEARCH_DEVICE_NOT_REACHABLE and SERVICE SEARCH _NO_
260. straction Layer Flash 100 MBit Bluetooth Memory Ethernet Baseband Figure 10 6 A structural overview of the HyNetOS for the Micro BlueTarget The Java Implementation The Java Virtual Machine for the Micro BlueTarget is an implementation of the Sun Microsystems Java 2 Micro Edition J2ME KVM CLDC V1 0 3 and has passed the CLDC Technology Compatibility Kit TCK In addition to providing the JSR 82 APls Smart Network Devices has provided additional libraries for Micro Blue Target development such as UDP datagram socket communication TCP stream socket communication a HTTP 1 1 libraries a RS 232 serial communication you can address ports COM1 COM5 Graphics library for monochrome LCD 12864 pixel a Java interface to ITU style keypad keys 0 9 File I O library For performance reasons and memory footprint size the TCP IP and the Bluetooth stacks were written in C and were implemented as asynchronous native processes The Java VM which exists as a native HyNetOS executable has its own internal thread scheduler A second process called the asynchronous event handler interfaces the asynchronous protocol software to the synchronous Java VM task So what does all this mean Once a Java thread makes a blocking I O call while waiting to receive data not only will all other native OS tasks be scheduled on the CPU but all other Java threads as well This approach ensures the best possible match of synchronous and
261. stroyed Those three states correspond to three methods startApp pauseApp anddest royApp One or more MIDlets packaged together in a JAR file constitute a MIDlet suite Software on the mobile device called the application manager is responsible for loading running and destroying the MIDlet The skeletal structure of a typical MIDlet looks like this import javax microedition midlet MIDlet public class MyApplcation extends MIDlet public MyApplication public void startApp public void pauseApp public void destroyApp boolean unconditional Note Sun has created a very handy tool for MIDlet development called the J2ME Wireless Toolkit The tool comes bundled with an emulator and can package compile preverify and run CLDC and MIDP applications The examples in this chapter use this tool and it is available free from the Wireless Java Web site htip wireless java sun com Using the MIDP User Interface Components The MIDP Ulis logically composed of two APIs high level and low level The high level API is primarily designed for business applications and it gives you objects like List TextBox ChoiceGroup and DateField This API includes a high level of abstraction because you can t define the visual appearance ie shape color font etc of those components When using the high level Ul components you won t have direct control of the navigation or scrolling or have direct access to the input devic
262. t Checks whether the listener attached to this filter should be notified of the specified event boolean containsBlipNodeID BluetoothAddress blipNodeID Checks whether the specified BlipNode ID is included in this filter boolean containsEventClass int eventClass boolean containsEventID int eventID boolean containsTerminalID BluetoothAddress terminalID Checks whether the specified terminal ID is included in this filter BluetoothAddress getBlipNodeIDs Returns a copy of the blipNoderps of the BlipServerEventFilter int getEventClasses Returns acopy of the eventClasses ofthe BlipServerEventFilter int getEventIDs Returns acopy of the eventTypes of the BlipServerEventFilter BluetoothAddress getTerminalIDs Returns a copy of the terminalrpsoftheBlipServerEventFilter Interface BlipServerEventListener public interface BlipServerEventListener This interface should be implemented by client classes wishing to listen to events generated by the BlipServer Package com ericsson blipnet api event Methods void handleBlipNodeEvent BlipNodeEvent e Called by the BlipServer event dispatcher when a BlipNodeEvent occurs void handleConnectionEvent ConnectionEvent e Called by the BlipServer event dispatcher when a ConnectionEvent occurs void handleObexEvent ObexEvent e Called by the BlipServer event dispatcher when an Obe
263. t BLIPNODE NOT WORKING ICON static int BLIPNODE SWUPGRADE ICON static int BLIPSERVER ICON static int COMPUTER DESKTOP ICON static int COMPUTER LAPTOP ICON static int COMPUTER PDA ICON static int COMPUTER SERVER ICON static int LAN ACCESS AVAIL ICON static int PHONE CELLULAR ICON static int PHONE SMARTPHONE ICON static int SESSION LAP ICON static int SESSION OPP_ ICON static int UNKNOWN DEVICE ICON Methods static getIcon ClassOfDevice classOfDevice boolean javax swing Imagelcon largelIcon Returns an ImageIcon illustrating the specified Class of Device static javax swing ImageIcon getIcon int iconId boolean largeIcon Returns a Imagelcon Copyright L M Ericsson A S Bluetooth Networks Interface BlipNode public interface BlipNode extends java io Serializable ABlipNode object contains information about a BlipNode Package com ericsson blipnet api blipserver Methods java lang String getBlipNodeFriendlyName Returns the friendly name of the BlipNode java lang String getBlipNodeGroupConfigurationName Returns the Configuration group of the BlipNode java lang String getBlipNodeGroupName Returns the group name of the BlipNode BluetoothAddress getBlipNodelID Returns the Bluetooth device address of the BlipNode java lang String getBlipNodeIP Returns the IP address of the BlipNode java lang String getUser Returns the user of the BlipNode if it was reserved at t
264. t is connected to the server or null if the BlipNode is not connected or the handle is already in use by another application BlipNodeHandle getBlipNodeHandleFromGroup java lang String blipNodeGroupName Returns a handle to the first available Blip Node from the specified BlipNode group BlipNode getBlipNodes java lang String groupName java lang String blipNodeGroupConfigurationName boolean includeReservedBlipNodes boolean includeDisconnectedBlipNodes Returns alist of BlipNodes which match the specified criteria BluetoothAddress getConnectedBlipNode BluetoothAddress terminalID Returns the Bluetooth device address of the BlipNode to which the specified terminal is connected BluetoothAddress getConnectedTerminals Returns a list of terminals currently connected to the server byte getObexObject java io File file Returns the contents of the specified file if the file is found on the server void releaseBlipNodeHandle BluetoothAddress blipNodeID Releases the handle to the specified BlipNode if the handle was reserved by this user void removeEventListener BlipServerEventListener listener Removes the specified listener from the server Class BlipServerConnectionException public final class BlipServerConnectionException extends BlipServerException Thrown by a BlipServerConnection if the connection to the server is lost Package com ericsson blipnet api blipserve
265. t to answer calls on your Bluetooth enabled wireless phone as well as answer calls on your Bluetooth enabled home phone You could also use the same headset to listen to your Bluetooth enabled portable radio Bluetooth can also be enabled in your car so that if you re driving and you receive a call on your wireless phone you can simply transfer the call to the hands free system built right into the car Your phone stays on your hip or in your briefcase You can also use the same technology to initiate a call in your car without touching your phone at all In either case if you ve arrived at your destination and you want to continue the conversation you just transfer the call back to the phone Bluetooth for Wireless Gaming Of course you can use Bluetooth for wireless gaming It s always a hassle when you want to connect two handheld video game systems and play against a friend Most cables were about 6 feet long so if both players were on a school bus they needed to sit right next to each other to play With Bluetooth you just have to come within range of your opponent to play Okay we re grownups now But what do you do if you re in a boring meeting and you have some time to kill With Bluetooth you and your equally bored colleague can both get out your PDAs and play a game of checkers PDAs are business tools so no one will ever know if you are taking down notes or getting double jumped Figure 1 2 shows a Bluetooth enabled mobile gaming d
266. t trans for int i 0 i lt transactionID length i if transactionID i trans transactionID i 1 return Completes a service search on each remote device in the list until al devices are searched or until an echo server is found that this applicati can send messages to private boolean searchServices RemoteDevice devList UUID searchList new UUID 2 i L1 Add the UUID for L2CAP to make sure that the service record found will support L2CAP This value is defined in the Bluetooth Assigned Numbers document searchList 0 new UUID 0x0100 Add the UUID for th cho service that we are going to use to the list of UUIDs to search for a fictional echo service UUID searchList 1 new UUID 00112233445566778899AABBCCDDEEFF false Start a search on as many devices as the system can support for int i 0 i lt devList length i System out printin Length devList length If we found a service record for th cho service then we can end the search if record null System out println Record is not null return true try System out printin Starting Service Search on devList i getBluetoothAddress int trans agent searchServices null searchList devList i this System out printin Starting Service Search trans addToTransactionTable tran
267. ta This is the Data From the Server Application to the Client Application byte datax strData getBytes con send datax System out println Data sent from the server side strData try Thread sleep 10 catch Exception e catch Exception e e printStackTrace Listing 9 5 shows the client code for our security demonstration Listing 9 5 ClientApp java import java io import javax bluetooth import com atinav standardedition io public class ClientApp implements DiscoveryListener private static LocalDevice localDevice null private DiscoveryAgent discoveryAgent null private String connectionURL null private RemoteDevice device null private ServiceRecord records null private boolean inquiryCompl false int count 0 int maxSearches 10 public ClientApp System out printlin n Atinav aveLink Bluetooth Client Application n System out printin n try localDevice LocalDevice getLocalDevice discoveryAgent localDevice getDiscoveryAgent device new RemoteDevice 10 System out printin n System out printin My BDAddress localDevice getBluetoothAddress System out printin Aaa ye Starts inquiry for devices in the proximity and waits till the inquiry is completed System out println nSearching for Devices n discoveryAgent startInquiry
268. tarts and is now looking for remote Bluetooth devices Figure 5 4 After a remote device is found we now go into stealth mode i e nondiscoverable Fiqure 5 5 The TDK USB Bluetooth device using a CSR Bluetooth radio Fiqure 5 6 The initial screen for the Piconet Browser application Fiqure 5 7 The Piconet Browser displays a list of Bluetooth devices in the area Fiqure 5 8 The Piconet Browser now displays the services offered by the remote device Chapter 6 Creating a Bluetooth Print Server with JPS API Figure 6 1 You can use the 3Com Wireless Bluetooth Printer Adapter in order to make a traditional i e non Bluetooth printer Bluetooth enabled Fiqure 6 2 Using the handy utility provided in this chapter you can turn your desktop into a Bluetooth print server Chapter 7 Java and OBEX Figure 7 1 OBEX is called IrOBEX in the IrDA protocol stack Figure 7 2 An OBEX header Figure 7 3 A sample message flow between OBEX clients and servers Chapter 8 Using a Bluetooth Simulator Figure 8 1 The Rococo Impronto Simulator version 1 1 installation screen Figure 8 2 The Rococo Impronto Simulator Console Figure 8 3 Creating a new Bluetooth device in the Simulator Console is pretty simple Figure 8 4 Configuring a cell phone in the Simulator environment Figure 8 5 The ChatServer Bluetooth device in the Impronto Simulator device list Figure 8 6 The ChatServer interacting with the ChatClient in the Impronto Simulator enviro
269. th import javax obex public class FTClient implements DiscoveryListener ocalDevice local null DiscoveryAgent agent null int attrSet null RemoteDevice btDev null String serviceURL null ClientSession con null HeaderSet hdr null public FTClient throws BluetoothStateException initialize the stack if needed local LocalDevice getLocalDevice agent local getDiscoveryAgent agent startInquiry DiscoveryAgent GIAC this public void deviceDiscovered RemoteDevice btDevice DeviceClass cod btDev btDevice System out println Device discovered btDevice getBluetoothAddress public void servicesDiscovered int transID ServiceRecord servRecord System out printin Discovered a service pag a for int i 0 i lt servRecord length i serviceURL servRecord i getConnectionURL ServiceRecord NOAUTHENTICATE true System out printin The service URL is public void serviceSearchCompleted int transID int respCode System out printin Service search completed mY System out printin Opening a connection with the server F _NOENCRYPT serviceURL NS try con ClientSession Connector open serviceURL hdr con connect hdr System out println Response code of the server after connect hdr getResponseCode Send
270. th using the L2CAP protocol This is ideal if you want to transfer items between two devices that can be broken into packets and reassembled again such as files L2CAP is a layer below RFCOMM in the Bluetooth protocol stack so if you optimize your MTU you can achieve significantly faster data transfers between wireless devices In Chapter 7 we ll examine a more robust Bluetooth protocol for transferring files OBEX Chapter 7 Java and OBEX Overview Whether you like it or not you re surrounded by objects every day In fact part of the role of being a good Java programmer is to find out what is the best way to recognize and create objects when developing business applications and games too As we stated in Chapter 4 the Bluetooth specification gives you three protocols to send and receive data RFCOMM for stream data a L2CAP for packet data OBEX for object data In this chapter we ll discuss the mechanics of the OBEX protocol and how to send objects between Bluetooth devices We ll cover the APIs in the javax obex package and finish things up by demonstrating how to send files between two devices using OBEX What Is OBEX OBEX which stands for OBject EXchange is a communication protocol that allows object data to be transferred between two devices it doesn t matter if those devices are wirelessly or physically connected OBEX was originally created by the Infrared Data Association IrDA but it later became one of
271. the Micro BlueT arget The vendor s program will read the data fror PLC via the Micro BlueTarget through COMM7 or COMM8 which are typical Serial Port Profile ports instead COMM1 or COMM2 Now let s say that all the preceding conditions exist but for some reason you can t Bluetooth enable the laptop read the data from the PLC Don t worry there s hope for you too All you need to do is attach another Micro Blue Target to your non Bluetooth enabled laptop and run the sPP2COMM program Since this Micro Blue Target collecting data over its serial port it will automatically run in client mode and look for a Serial Port Profile server then read the data from the Serial Port Profile server and pipe that data to its own serial port Your laptop can t the vendor program to read and interpret the PLC data this time via two Micro Blue Targets through a tradition port like COMM1 or COMM2 In this case you have made a Serial to wireless bridge Now let s say that you re in a very special situation in that the vendor doesn t make a program to read and inter data from the PLC Now you can be really creative and just make your own In this case all you need is a JSR enabled client device like a PDA or laptop and you have to make a slight modification to SPP2COMM progra the client mode part of it instead of sending the data to the COMM port just interpret display or process it Summary In this chapter you were introduced to one of the first fully
272. the other hand a simulator is something usually software that represents the functionality of an entire system A simulator will mimic the interaction and communication process between devices in the system and try to display the results as if those occurrences actually happened For instance an automotive company can create a crash test simulator Using this simulator the automotive engineer can simulate what would happen to the car if it collides with another object like a wall a deer or even another car Now in order for the simulator to be even remotely useful formulas must exist that describe the interaction of the objects in the system If such formulas do not exist then a lot of mapping and modeling of the objects in the system need to be done ahead of time before the simulator is created With the use of a Bluetooth network simulator you can mimic the interaction of multiple Bluetooth devices on your desktop computer as if those occurrences were actually happening between Bluetooth devices The Pros and Cons of Using a Simulator A Bluetooth simulator can be a useful and beneficial tool One of the major benefits of a Bluetooth network simulator is that it allows you to work on your application code without worrying about setting up and administrating your Bluetooth hardware configurations This enables you to create quick proof of concepts and algorithm verification In larger development teams the use of a simulator can greatly r
273. ther words if you want to send a picture from the camera to the PDA then you ll need to use the computer to interconnect them The same also goes if you want to scan a document and send it to the printer i e to act like a copier or send it to the PDA you ll always need your PC to be the man in the middle Of course you can buy a cable or two to do some of those tasks but those cables are rare and expensive Bluetooth solves all this by allowing your devices to communicate among themselves with no hassle and with no cables It s essentially the universal cable Bluetooth in the Small Office or Home Office In the small office setting how do you share peripherals like a printer among users Let s say you have a 300 printer that you want two users on your network to share Your cheapest option is to buy a print server but that s another 300 You might as well buy another printer for that kind of money With Bluetooth if both your users are in range no print server is needed because both users can connect to the printer as if it were a local printer For that matter the printer should be able to print for every Bluetooth user within range but remember that it can only handle seven active connections at the same time Bluetooth for Voice Applications Now Bluetooth is great at transferring data wirelessly but it also has the capability to transmit voice and sound as well So if you had a Bluetooth headset you could use the same headse
274. ting with an external Bluetooth piconet Summary In this chapter we gave you an overview of the principles and concepts of Jini network technology We also presented an overview of the hows and whys for integrating Bluetooth and Jini together in order to create some really cool wireless applications Both Jini and Bluetooth complement each other for creating networked applications Jini brings to the table advanced networking capabilities such as leasing and distributed events while Bluetooth allows the members of the network to be small power efficient and wireless Appendix A javax bluetooth This appendix contains all the fields and method signatures of the classes interfaces and exceptions that comprise the javax bluetooth package of the JSR 82 API Class BluetoothConnectionException fields static int FAILED NOINFO static int NO RESOURCES static int SECURITY BLOCK static int TIMEOUT U U static int UNACCEPTABLE_PARAMS static int UNKNOWN_PSM constructors BluetoothConnectionException int error BluetoothConnectionException int error java lang String msg methods int getStatus Class BluetoothStateException constructors BluetoothStateException BluetoothStateException java lang String msg Class DataElement fields static int BOOL static int DATALT static int DATSE static int INT 1 static int INT 16 static
275. to each other If this example doesn t work then you need to troubleshoot your setup and configuration So how does it work Well as shown in Figure 10 9 one board is offering an echo service to the public The board is the client that is using that service and is sending messages to the server i 10 9 Micro BlueTarget Micro BlueTarget 1 Client 2 Server Figure 10 9 The L2CAPEcho Service Since this example contains most of the foundational elements that were described previously in this book we into further explanation other than the fact that the client sends a message once per second to the server The reads the message from the Input St ream and writes it back to the OutputStream and the client gets the n back as an echo Listing 10 1 shows the code for the L2CAPEchoServer Listing 10 1 L2CAPEchoServer java import java lang import java io import javax microedition io import javax bluetooth public class L2CAPEchoServer static ClientProcess Client null public static void main String args L2CAPConnectionNotifier Server null try cat try cat sys whi ocalDevice local LocalDevice getLocalDevice ocal setDiscoverable DiscoveryAgent GIAC ch BluetoothStateException e System err printin Failed to start service System err printin BluetoothStateException e getMessa
276. to point 15 Device discovery 55 57 Device driver 17 Device management 25 51 55 Device Manager Windows 2000 25 DeviceClass class javax bluetooth 53 57 58 261 Device Discovered method 57 DeviceProperties java listing 48 51 Devices Bluetooth SeeBluetooth devices Dial up networking wireless 5 Dial Up Networking Profile 26 DISCONNECT operation OBEX 132 Disconnect method of ClientSession object 132 Discovery modes Bluetooth 52 Discovery Service Jini 244 DiscoveryAgent class 52 56 57 63 64 261 DiscoveryListener interface 57 64 261 262 Distance measuring 34 Distributed computing problems of 242 Doc interface 100 DocFlavor object 100 DocPrintJob object 101 Documents in JSP 99 101 Dynamic OS loader 189 Index E E mail stations in a hotel 229 Echo service 193 207 Embedded Linux 185 Embedded Windows 185 Employees tracking in a building 229 Emulator vs simulator 138 Encrypt parameter in connection URL 161 162 174 177 Encrypt method of RemoteDevice class 162 Encrypted data decrypting 176 178 Encryption 159 163 Encryption algorithm cipher 159 Encryption key 159 161 Enterprise Bluetooth applications 225 240 creating using Java 226 qualifications of 225 Ericsson 11 12 Ericsson BlipNet SeeBlipNet Events Jini 245 Events JPS 99 Example code in this book working with 81 Index F FAILURE response code OBEX 121 125 FAX Profile 26 File
277. tooth device tracker will help grocery store manager to answer the following questions m Are customers wandering around aimlessly Doconsistent buying patterns exist m Which are the frequently traveled aisles a Are the aisles arranged properly How long are customers in the store All these factors impact customer satisfaction and directly affect whether or not if the customer will return Tracking java is a simple enterprise Bluetooth application that allows you to track Bluetooth devices using t Ericsson BlipNet Of course before you run Tracking java you have to have at least two BlipNodes connec to your BlipServer otherwise it would be pointless to track devices with only a single node Another prerequisil that a user name and password to the BlipServer must already be created In this example the user name is Tracking and the password is Tracy You also need to assign the BlipNodes that you want to perform device tracking to a group In this example the group is called First_Floor Note Of course you can create user names passwords and groups using the BlipManager application In order to run the application and to track every discoverable Bluetooth device just execute the following statement at the command line java Tracking First_Floor If you want to track specific Bluetooth clients then you need to provide their Bluetooth address at the commanc line separated by spaces java Tracking First Floor 001122334455
278. tooth specification So what happens to the piconet if a new Bluetooth device wants to join the piconet after the master has acquired seven slaves Does it shut down Will older members of the piconet get kicked off No actually the master of the piconet will not invite new members to join until at least one the old members leaves or goes into an inactive state Now on the other hand if one of the slaves in the Bluetooth piconet also happens to be multipoint capable then the newcomer can create a piconet with that slave thereby creating a scatternet as shown in Figure 2 11 A scatternet will also be created if the master of the existing piconet becomes a slave to the newcomer Slave Slave Slave Master Figure 2 11 A scatternet is formed when a slave in one piconet is the master in another piconet The Bluetooth Qualification Process Okay so what does it take to turn a product that uses Bluetooth technology into an official Bluetooth certified product Well you first need to join the Bluetooth SIG How do you join Just go to http www bluetooth org and fill out the membership form After becoming a member you need to submit your product for testing by a Bluetooth Qualification Body The Qualification Body will test your device against the current Bluetooth specification as well as interoperability with other devices that use your Bluetooth profiles Note Java developers really don t need to join the Bluetooth SIG or undergo
279. tworking n a 4609 0x1201 Now let s take a look at the constructors for UUID public UUID long uuidValue This is pretty cut and dry it constructs a UUID object from a long public UUID String uuidValue boolean shortUUID This method allows you to construct a UUID from a String representation of a UUID If short UUID is set to true then a short UUID is returned one that is made up of 16 bits instead of 128 bits Note When using this method be sure not to include the 0x prefix in front of the St ring when constructii this object javax bluetooth DiscoveryAgent Hey wait a minute didn t we use this class for device discovery Well that s why the authors of the Java Bluetooth specification named this class DiscoveryAgent because they intended this class to be used for be device and service discovery In order to find services on remote devices you ll use either select Service searchServices public int searchServices int attrSet UUID uuidSet RemoteDevice btDev DiscoveryListener discListener This method allows you to search for alist of services on a single remote Bluetooth device The attrSet parameter must be populated with an array of integers that correspond to attributes that you want to see when the services match the UUIDs The UUID parameter is the list of UUIDs of services that you want to look for RemoteDevice is the reference to the remote device that you want to search for services You must al
280. ty Because the JSR 82 is the official Java API for Bluetooth all vendors who implement the standard must include a core set of layers and profiles in their Bluetooth SDK A JSR 82 compliant Bluetooth stack must include the following layers Host Controller Interface HCI Logical Link Control and Adaptation Protocol L2CAP m Service Discovery Protocol SDP a RFCOMM These profiles are also required m Generic Access Profile Service Discovery Application Profile Serial Port Profile a Generic Object Exchange Profile CROSS See The Bluetooth Protocol Stack and Profiles in Chapter 2 for details on the REFERENCE Bluetooth protocol stack and profiles just in case you forgot The first thing that may come to your mind is Hey wait a minute doesn t the Bluetooth specification contain more profiles than that Why did they implement only a few profiles in Java Well here are two major reasons First of all the JSR 82 team wanted to get the Java Bluetooth specification in the hands of developers as quickly as possible Recall in Chapter 2 that Bluetooth profiles are designed to be functional enough where higher profiles extend the functionality of the lower or base profiles Refer to Figure 2 9 which shows a diagram of the relationship of the profiles of the Bluetooth specification Secondly by implementing the base profiles Generic Access Profile Service Discovery Application Profile Serial Port Profile and Generic Object
281. ublic FTServer throws BluetoothStateException initialize the stack if needed public int onConnect HeaderSet request HeaderSet reply pub c e ret pub System out println A OBEX connection has received return ResponseCodes OBEX_HTTP_OK lic int onGet Operation op try The server has received a GET request for client System out printin Received a GET request from client HeaderSet hdr op getReceivedHeaders System out printin Server has received a request for the file hdr getHeader HeaderSet NAME toString String url file name hdr getHeader HeaderSet NAME toString mode r InputConnection inpcon InputConnection Connector open url InputStream in inpcon openInputStream byte fileAsBytes new byte 97 in read fileAsBytes System out printin File read fully into the port for int i 0 i lt fileAsBytes length i System out print char fileAsBytes i DataOutputStream out op openDataOutputStream out write fileAsBytes 0 fileAsBytes length System out println n File written back to client op close in close atch IOException e System out println e getMessage atch ArrayIndexOutOfBoundsException e System out println e getMessage urn ResponseCodes OBEX_HTTP_OK lic stati
282. uetooth 41 Stack initialization 4 51 95 Stack initialization code for Atinav SDK 47 Stack layers JSR 82 compliant Bluetooth 39 Startinquiry method DiscoveryAgent object 56 57 Stealth mode nondiscoverable mode 81 88 Stealth Mode example 81 88 Stealth java listing 84 87 Stream ConnectionNotifier object 66 SUCCESS response code OBEX 121 125 Sun Microsystems Java 2 Micro Edition SeeJ2ME platform Sun Microsystems Jini SeeJini Symmetrical encryption 159 161 Synchronization Profile 27 System monitor console Micro BlueT arget 189 System trace window Micro BlueTarget 190 Index T TCK Technology Compatibility Kit 36 TCP IP based Bluetooth profiles 252 TCS Telephony Control Protocol Specification 21 TCS BIN 21 TCS Binary 21 TDK Bluetooth Developer s Kit 271 TDK USB Bluetooth device 83 84 Testing using Bluetooth simulator for 137 153 Text messages example 145 152 Thread scheduler 187 TINI Tiny Internet Interface 254 255 TINI chipset 254 TINI devices 255 TINI microcontroller 255 Tracking employees in a building 229 TrackingEventListener class 235 Tracking java 234 240 Tracking java listing 235 240 Transactions Jini 245 Triangulation 34 Trusted devices 158 TYPE headers OBEX 122 Index U UART device 183 Unicast request LUS 247 250 UUID Universal Unique Identifier 61 UUID class javax bluetooth 61 63 264 UUID methods 62 63 UUID
283. uipment isn t cheap so also want to acknowledge all the great companies around the world literally that gave Ranjith and me hardware loans and technical assistance For instance Jeff Day and the rest of the team at 3Com including Ken Morley Brent Nixon and Randy Rollins were very helpful in providing us with Bluetooth adapters and tech support Mahendra Tailor from TDK Systems in the UK was very helpful in providing us with equipment as well Rococo was very kind to allow us to have an extended evaluation period in order to write the chapter on Bluetooth simulation Thanks to Geraldine Karl and the rest of the team in Ireland Lim Siong Huat from Mobiwave in Singapore was very helpful in allowing us to use their protocol analyzer for the security chapter Peter Duchemin from Smart Network Devices in Germany was very helpful in getting me the inside scoop on their Micro BlueTarget also want to thank Niels Christian Gjerrild from Ericsson in Sweden for hardware and documentation on the Ericsson BlipNet system North of the border in Canada also received assistance from Dr Steven Knudsen regarding the integration of Jini and Bluetooth This is my first book so definitely have to thank all the wonderful teachers at Grant Cass Tech and WSU who helped me to get here You ll never forget a good teacher and I ve had many in my lifetime want to thank personally Mrs Smith Mrs Parent Mr Walker and Mrs Cowan from Grant School At Cass
284. ulator Overview Okay we have to admit it If you re new to Bluetooth developing wireless client server code can sometimes be rather inconvenient After writing the client code and then the server code you may have to do a lot of debugging to get things working properly Maybe your logic is incorrect perhaps you have a problem with one of your Bluetooth modules maybe both of them With so many points of failure it can be a real daunting task to debug even the simplest Bluetooth application However with the help of a Bluetooth network simulator all of the hardware and its underlying complexities are abstracted and this will enable you to focus more time and effort to debug your application code Note A Bluetooth network simulator can also be helpful if you re on a budget or if you re a student If either case applies to you you certainly don t have a lot of money to buy a test lab full of Bluetooth devices This chapter is all about how to use a Bluetooth network simulator in your application development process A Bluetooth network simulator isn t a panacea for all of your development woes but it can be a very useful tool in many areas of the wireless application development life cycle We ll start this chapter off by explaining the difference between a simulator and an emulator just in case you didn t know that there s a difference Next we ll take a look at the pros and cons of using a simulator In the rest of the chapter we ll g
285. up Service will keep the service registered for at least that length of the lease requested or provide a duration of its own It s up to the Service Provider to renew the lease as required After the ServiceItem is registered with the Lookup Service the Service Provider has joined the federation lockup Service Servicelten Registers Serviceites h h Service Consumer Service Provider i AJ i N Figure 12 3 The Service Provider registers its ServiceItem with the Lookup Service Note The leasing mechanism is an important part of Jini technology because it allows devices to clean up unused resources If a lease expires or if it can t be renewed because the lease grantor or holder has left the federation the associated resource can be released Now that we have a federation with a Service Provider in it it s time to look at things from the Service Consumer s perspective The Lifecycle of a Service Consumer The Service Consumer also starts its life cycle by discovering a Lookup Service It uses the same discovery mechanisms that a Service Provider uses The Service Consumer can use any of the three discovery mechanisms but in this scenario let s say that the Service Consumer is using a multicast request to find a Lookup Service This is illustrated in Figure 12 4 Lookup Service A 1 Servicelten Response Including ServiceRegistrar Service Consumer Service Provider Servicelten
286. use of a resource in a Jini federation is granted for a specific amount of time This concept is known as a lease The duration of the lease may be fixed by the grantor or negotiated To maintain the use of a service including services joined to Lookup Services the lease must be renewed periodically This allows for the expiration and cleanup of services that are no longer required or whose owners have left the federation Transactions Atransaction allows a set of operations to be grouped in such a way that they either all succeed or all fail To the members of the federation the group of operations in the transaction appear to function as a single unit Events An object residing on a device may register an interest in an event occurring in another object residing on a different device in the federation and receive notification when the event occurs Thus events provide a mechanism for maintaining consistency of state information in the federation How Jini Works So let s first define a Jini ServiceItem A Serviceltem is comprised of a service object and some attributes The only real restriction on ServiceItem objects is that they be serializable There are typically three entities involved in a Jini federation a Service Providers are the entities that provide a Java based software service The service can be pretty much anything and doesn t necessarily have anything to do with the device that hosts the provider For instance a
287. vailable at http www apress com in the Downloads section The book s companion Web site http www javabluetooth com also contains the source code as well as other useful resources such as alist of recommended Bluetooth hardware for running the examples Chapter 1 Introducing Bluetooth Simply stated Bluetooth is a wireless communication protocol As such you would use Bluetooth to communicate to two or more other Bluetooth capable devices In this sense Bluetooth is like any other communication protocol that you may use every day like HTTP FTP SMTP or IMAP Bluetooth is also like these protocols in that it has a client server architecture In Bluetooth the one who initiates the connection the client is the master and the one who receives the connection the server is the slave The purpose of this chapter is to give you an introduction to Bluetooth We ll briefly compare it with competing technologies like Infrared and 802 11b and explain where Bluetooth fills the gaps that these other technologies leave open Next we ll show you what Bluetooth can do and where it is currently used in applications today just in case you re unfamiliar with the capabilities of the technology Finally we ll wrap up this chapter with a few scenarios for how Bluetooth will be used in the near future Bluetooth vs Infrared Of course wireless communication between two computers is not new PDAs have been able to do that for years using infrared tech
288. velop deploy and test your Java Bluetooth applications all within the environment of your development machine Figure C 2 The MIDP Chat application List of Tables Chapter 2 Bluetooth 1 1 Table 2 1 Common Radio Frequencies Table 2 2 Bluetooth Device Power Classes Table 2 3 Layers of the Bluetooth Protocol Stack Chapter 3 Before You Get Started Table 3 1 Classes in the javax bluetooth Package Table 3 2 Classes in the javax obex Package Table 3 3 Java Bluetooth SDK Vendors Chapter 4 Understanding the Java Bluetooth API Table 4 1 Bluetooth Discovery Modes Table 4 2 Bluetooth Major and Minor Device Classes Table 4 3 Common UUID Values for Bluetooth Protocol Layers Table 4 4 Common UUID Values for Bluetooth Profiles Chapter 7 Java and OBEX Table 7 1 OBEX Headers in the java obex HeaderSet Interface List of Listings Chapter 4 Understanding the Java Bluetooth API Listing 4 1 Stack Initialization Code for the Atinav SDK Listing 4 2 BluetoothSetup1 java Listing 4 3 DeviceProperties java Listing 4 4 The Service Registration Process Listing 4 5 Opening Connections on a Bluetooth Server Chapter 5 Bluetooth with J2ME MIDP Listing 5 1 Stealth java Listing 5 2 BeamT sk java Listing 5 3 PiconetMIDlet java Chapter 6 Creating a Bluetooth Print Server with JPS API Listing 6 1 JPSPrint java Listing 6 2 JPSBluetoothPrint java Listing 6 3 JPSBluetoothPrintClient java Chapter 7 Java and OBE
289. vents ConnectionEvents and ObexEvents are occurring The com ericsson blipnet api event package also includes the ObexProgressListener interface which you can use to determine the progress of an OBEX object transfer When dealing with clients that support the Object Push Profile the classes that form the com ericsson blipnet api obex pushobjects package come in handy This package contains classes such as ObexFile and ObexGenericObject that help you when you re sending or receiving OBEX objects For obvious reasons the com ericsson blipnet api util was designed to be a utility package but at the moment it only contains a single class for icons BLipNetIcons CROSS See Appendix D for a complete list with descriptions of all the classes and REFERENCE interfaces of the BlipNet 1 1 API Now that you have a good understanding of the BlipNet architecture and its APIs let s look at an example demonstrating how to create an enterprise Bluetooth application using the Ericsson BlipNet The Bluetooth Device Tracker A Bluetooth device tracker is an extremely useful enterprise Bluetooth application but it s really an invaluable tc to anyone in the retail business Why Have you ever been to a grocery store where the peanut butter is in aisle two but the jelly is located in aisle twelve Or even worse the coffee and the cream are eight aisles apart In the near future almost every mobile phone will be Bluetooth enabled so a Blue
290. verEventListener extends java rmi Remote Defines the handle Event method for notifying event listeners of BlipServer events The interface is used internally by the BlipServer API and should never be implemented by client applications Package com ericsson blipnet api event Methods void handleEvent Event event Interface RemoteObexProgressListener public interface RemoteObexProgressListener extends java rmi Remote Defines the newProgress method for notifying event listeners of Push progress events The interface is used internally by the BlipServer API and should never be implemented by client applications Package com ericsson blipnet api event Methods void newProgress ObexProgressEvent e Class ScanMode public final class ScanMode extends java lang Object implements java io Serializable ThescanMode class encapsulates the different Scan Modes supported by the BlipNode Package com ericsson blipnet api Bluetooth Fields static java lang String FRIENDLY_NAMES T Friendly names of the defined Scan Modes static int INQUIRY_AND_PAGE_SCAN_DISABL El J Inquiry Scan Disabled Page Scan Disabled static int INQUIRY_AND_PAGE_SCAN_ENABLED Inquiry Scan Enabled Page Scan Enabled static int INQUIRY_SCAN_ENABLED Inquiry Scan Enabled Page Scan Disabled static int PAGE_SCAN_ENABLED Inquiry Scan
291. viceList copyInto devList if searchServices devList return record return null This is the main method of this application public static void main String args SPP2COMM client null SppServerProcess server null int baudrate Validate the proper number of arguments exist when starting this application if args null args length 1 System out printin usage java SPP2COMM lt baudrate gt return Create a new SPP2COMM object EEY client new SPP2COMM catch BluetoothStateException e System out printin Failed to star System out printin BluetoothState Bluetooth System xception e getMessage Gl Ct get the baudrate for the serial port from the command line baudrate Integer parseInt args 0 make the connection to the serial port try get the connection serialport StreamConnection Connector open comm 1 baudrate baudrate Connector READ WRITE true catch Exception e System out printin serial port open exception e System exit 0 open the serial port s output stream try ser out serialport openOutputStream catch Exception e System out printin serial output stream open exception e System exit 0 open the serial port s input stream try ser in serialport openInputStream catch Exception e
292. viceRecord DataElement and UUT objects in regard to how they all work together for service discovery Service Record Service SDDB Record Figure 4 1 Service records in the SDDB As you can see in Figure 4 1 a service record is an individual entry in the SDDB Service Discovery Database Entries in service records are called attributes Attributes consist of an ID and value See Figure 4 2 for an illustration 0x0000 DataElement int 0x0001 DataElement UUID 0x0002 DataElement int 0x0003 DataElement boolean Attribute ID Attribute Value 0x0000 DataElement int Figure 4 2 An individual attribute of a service record Attribute IDs are 16 bit unsigned integers Ox000 OxFFFF In a ServiceRecord object attribute values are stored as DataElement objects as shown in Figure 4 3 Attributes Attribute ID Attribute Value 0x0000 DataElement int Figure 4 3 An illustration of a service record attribute DataElements can be created from the following Java types int boolean UUID and Enumeration see Figure 4 4 DataElements DataElement int DataE lement UUID DataE lement int DataE lement boolean Figure 4 4 DataElements Figure 4 5 wraps it all up by showing the process of service discovery for a PDA that wants to use the services a Bluetooth keyboard A successful service discovery will occur only if there is a match in the UUID of a service record in the SDDB of th
293. ware configuration 182 184 hardware details 184 HyNetOS 185 191 Java implementation 186 187 JVM for 186 187 libraries 186 1 87 memory map of 188 operating environment components 185 operating system for 185 191 operating system tools 189 190 programming 190 224 software configuration 185 187 standard version 180 Starter Kit 180 184 what it is 179 182 Wireless Network Access Point 191 192 MiDlet suite 78 MiDlets defined 78 developing 78 80 JAD Java Application Descriptor file 144 skeletal structure of 78 79 MIDP Mobile Information Device Profile 75 96 high level API and low level API 79 packages for mobile devices 77 user interface components 79 MIDP 1 0 device qualifications for 77 MIDP 2 0 specification 77 MIDP 2 0 wireless application functionality 77 78 MIDP Chat application 272 Mobile phone configuring in Impronto Simulator 143 and laptop connection sharing 5 limitations of 3 and PDA data transfer 3 4 Mobiwave BPA D10 Bluetooth Protocol Analyzer 163 173 1 78 data captured by 174 175 data transmission sniffing 173 Motorola 35 MTUs Maximum Transmission Units 70 71 Multicast announcements LUS 247 Multicast requests LUS 247 250 Multipoint device communication 16 Museum environment 226 Mydevice xml listing 143 Index N NAME headers OBEX 122 Node administration BlipManager 231 232 Nokia N Gage gaming system Bluetooth enabled 7 Nondiscover
294. ware or OS used for your PDA mobile phone watch etc you can use the same programming language to create your Bluetooth applications This book is all about how to create wireless applications using Java and Bluetooth How This Book Is Organized Here s an overview of what s covered in this book Chapter 1 Introducing Bluetooth f you re completely new to Bluetooth then this chapter is for you In Chapter 1 we give a brief introduction to Bluetooth with a general explanation of what you can do with the technology Chapter 2 Bluetooth 1 1 In this chapter we dive right into the dirty details of the Bluetooth protocol Here we define the roles and relationships between the Bluetooth stack Bluetooth profiles and Bluetooth hardware If you ve seen Bluetooth terminology before but you don t know the difference between SDP and SDAP for instance then this chapter will help clear things up Chapter 3 Before You Get Started Chapter 3 is very appropriately named because it covers all the loose ends that need to be addressed before we show you how to integrate Bluetooth and Java Chapter 4 Understanding the Java Bluetooth API This chapter covers the full life cycle of a Bluetooth application whether you re using Java or not This chapter also shows you how to use the javax bluetooth package of the official Java Bluetooth API the JSR 82 in order to create Bluetooth applications Chapter 5 Bluetooth with J2ME MIDP The first complete ex
295. ws platforms this file is located at simulator_home bin setEnvVars bat On UNIX platforms the file is located at simulator home bin setEnvVars sh After the script has executed successfully navigate to the examples directory and type ant at the command pr to build the examples Note Just in case you didn t notice the Apache Ant build utility was installed with the Impronto Simulator The final step is to start up the Simulator Console All you need to do is go back to the bin directory and execu manager A screenshot of the Simulator Console is shown in Figure 8 2 Eton maden Cones loca 101 fe Device Coangury Hep Blastouth Adukess Friendly Narre Connectabie Device Oass Miccelianecus No minn device Positioning Motwerkng Reader irg Capturing Service Classes Otyect Transfer Devices on Telephony nfermaton Discovery Moor Not atsc over albe Security Mode Never enforce security Save Changes Figure 8 2 The Rococo Impronto Simulator Console Working with the Simulator Console The Simulator Console is the control panel to the Impronto Simulator Using the Simulator Console you can cr and edit simulated Bluetooth devices The characteristics of each device that you create are storedin an XML fi theconfig directory For instance to create a new Bluetooth device just go to the File menu and select New Device as shown in Figure 8 3 fE umer vet Sima ation Console localhost lgj xi Hie Levee Comigure
296. xEvent occurs Class BlipServerException public class BlipServerl Exception extends java lang Exception Superclass for all exceptions which can be thrown by the BlipServer Package com ericsson blipnet api blipserver Constructors BlipServerException BlipServerExcepti on java lang String s BlipServerExcepti on java lang String s java lang Throwable e Class BluetoothAddress public final class BluetoothAddress extends java lang Object implements java io Serializable TheBluetoothAddress class models a Bluetooth Device Address BD_ADDR This is a 48 bit unsigned integer often written in hexadecimal Objects of the BluetoothAddress class are immutable once created they cannot change This class provides the equals and hashCode methods for use in connection with the Collection classes Package com ericsson blipnet api Bluetooth Constructors BluetoothAddress byte bluetoothAddress Constructs a BluetoothAddress object from a byte BluetoothAddress java lang String bluetoothAddress Constructs a BluetoothAddress object from a String Methods boolean equals java lang Object obj Compares this BluetoothAddress with an Object and returns true if they are equal byte getBytes int hashCode Returns ahashCode for this BluetoothAddress java lang String toString Returns a String representation of this BluetoothAddress
297. xType Returns the mime type of this ObexPushObject Interface Event public interface Event extends java io Serializable The superclass of all events T his interface defines common event methods and contains event ID definitions for all events Package com ericsson blipnet api event Fields static int BLIPNODE_ALARM T Indicates that a critical condition has occurred in a BlipNode connected to the server static int BLIPNODE_DEREGISTERED Indicates that a BlipNode has disconnected from the server static int BLIPNOD T _ EVENT Event class of BlipNode related events T static int BLIPNOD _ LOCKED Indicates that an application has acquired the lock on a BlipNode static int BLIPNODE_REGISTERED Indicates that a BlipNode has connected to the server static int BLIPNOD T RELEASED Indicates that an application has released its lock on a BlipNode static int BLIPNODE_STARTUP_FAILED Indicates that a BlipNode attempted to connect to the server but the startup failed for some reason static int BLIPNODE SW UPGRADE COMPLETE Indicates that a BlipNode software upgrade has been completed successfully static int BLIPNODE SW UPGRADE FAILED Indicates that a BlipNode software update failed static int BLIPNODE_SW_UPGRADE_STARTED T In
298. y would anyon use RFCOMM instead of L2CAP to send data or vice versa Well RFCOMM is also known as the virtual serial port communication protocol An ideal way to use RFCOMM is in situations when you would replace a serial cable For instance if you were a developer for a GPS manufacturer and your duty was to make one of their units Bluetooth enabled then RFCOMM would be a likely choice in this scenario Why The GPS unit will alway have a constant stream of information that needs to be processed rendered calculated etc So collect the da from your stream and plot those coordinates on the screen On the other hand L2CAP is great for handling packet data L2CAP can easily be used and actually is asa data multiplexer You can read data from the connection and based upon a header in the packet you can rout that data to different methods threads and classes in your application Summary This chapter gave you a formal introduction to the official Java Bluetooth APIs You should be aware of all the basic components of a Bluetooth application as well as how to implement them using the classes and interfaces of the official Java Bluetooth API This chapter also discussed the importance and the roles that the Bluetooth Control Center BCC plays in your wireless applications Essentially this chapter showed you how a Bluetooth application works by its components In the next chapter we ll look at a full working example of a Java Bluetooth appli
299. you may have already guessed this application won t work if you use a JSR 82 compliant Java Bluetooth development kit Why Well as we stated in Chapter 3 the official Java Bluetooth API has a dependency on the Generic Connection Framework GCF to exist which unfortunately is not a par of the J2SE JDK 1 4 That doesn t mean that Java Bluetooth development kits don t exist for the J2SE In fact Atinav Rococo and Zucotto all make Java Bluetooth development kits for the J2SE At the time of this writing Atinav s and Rococo s J2SE implementation closely matches that of the JSR 82 implementations The next example uses the Atinav J2SE Bluetooth development kit Listing 6 2 is the server code for the wireless print server example JPSBluetoothPrint java As you can see it is simply the JPSPrint java example with a little Bluetooth code thrown in All the wireless functionality is encapsulated inthe method connect ToClientAndPrint When this method is called the server will wait until a client attempts to connect at an L2CAP channel After the client connects and sends a file the server will attempt to print it with its printFile method Listing 6 2 JPSBluetoothPrint java import java io import javax print import javax print event import javax print attribute import javax print attribute standard import javax bluetooth import com atinav standardedition io class PrintStatus implements PrintJobListener
300. you probably have already assumed this method returns to you the 12 character Bluetooth address of the remote device public String getFriendlyName boolean always Ask Knowing the Bluetooth address of the Remot eDevice is fine but it is even better to know the friendly name c that device The friendly name of a Bluetooth device is something like Andrew s PDA Home Office Printer Ranjith s MP3 Player javax bluetooth DeviceClass This class represents the class of device in the Bluetooth specification A device class is simply a classification Bluetooth devices Why is this class useful Well by simply calling the methods of this class you can determin what kind of devices are in the area like computers laptops phones PDAs access points etc The methods provided to accomplish this task are getMinorDeviceClass and getMajorDeviceClass both of which return an int Table 4 2 shows some common major and minor device classes Table 4 2 Bluetooth Major and Minor Device Classes l MAJOR MINOR MAJOR CLASS MINOR CLASS DESCRIPTION CLASS CLASS DESCRIPTION 0 Misc major device 256 0 Computer Unassigned misc 256 4 Computer Desktop 256 8 Computer Server 256 12 Computer Laptop 256 16 Computer Sub laptop 256 20 Computer PDA 256 24 Computer Watch size 512 0 Phone Unassigned misc
301. you three ways to send and receive data but for right now we ll cover only two of them RFCOMM and L2CAP RFCOMM Connections As you may remember from Figure 2 9 the most common Bluetooth profiles use the Serial Port Profile as a foundational layer Note RFCOMM is the protocol layer that the Serial Port Profile uses in order to communicate but these tw items are almost always used synonymously Sessions and Connections Before we continue there s a little more terminology to introduce here sessions and connections You can onh have a single session between two Bluetooth devices This limitation isn t a big deal per se because the definition of a session is simply one or more connections shared between two devices You can also relate a Bluetooth session in the same way that sessions are created and used on the Web When a Web server is communicating to a Web client there is only one session although there are numerous connections Now a Bluetooth device can have multiple sessions only if each session is linked to a different device This also applie on the Web powerful application servers have the capability to create multiple sessions and keep them in memory but each session is linked to a different client Server Connections with the Serial Port Profile Listing 4 5 demonstrates what is needed to open connections ona Bluetooth device that will act as a server Listing 4 5 Opening Connections on a Bluetooth Server let s nam
302. ystem out printin Inquiry completed synchronized this Unblocking the wait for inquiry complete try this notifyAll catch Exception IntE System out printin IntE getMessage public void getServices UUID uuids new UUID 1 uuids 0 new UUID 6666 true try if btDev null System out printlin No device has been discovered hence not worth proceeding exiting System exit 1 System out printin Now searching for services a MER agent searchServices attrSet uuids btDev this catch BluetoothStateException e System out printin e getMessage System out printin Got an exception so exiting System exit 1 synchronized this Waiting for Service Search to be completed try this wait catch Exception IntE System out printin IntE getMessage public boolean sendFile String fileName try 12capConn L2CAPConnection Connector open serviceURL InputConnection inConn InputConnection Connector open file name fileNamet mode r InputStream fileReader inConn openInputStream int maxSendMTU l2capConn getTransmitMTU byte buffer new byte maxSendMTU sending fileName assuming for the time being that the fileName will not be greater than 48 bytes 1l2capConn send fileName getBytes System out printin Send the file Name fileName sendin
303. ystem out printlin Bluetooth output stream write exception e else System out printin No SPP peer found do we have a Bluetooth connection already if bluetoothport null do we have an InputStream on the Bluetooth connection already if bt_in null no then create on try bt_in bluetoothport openInputSstream catch Exception e System out printin Bluetooth output stream open exception e listen on the bluetooth connection rxlen 0 try read in as many bytes from the serial port as currently available but do not exceed the current buffer length The read method blocks but is periodically released by an InterruptedIOException in order to allow other things to happen meanwhile while true data bt_in read rxdata rxlen byte data rxlent if rxlen gt 64 data 1 break System out printin data received from bluetooth port len rxlen catch InterruptedIOException e System out printin Bluetooth port receive timeout e catch Exception e System out printin Bluetooth port receive exception e try System out println ser_out write rxdata ser_out flush i catch System out println Exception e send Bluetooth data on serial link Bluetooth output stream write exception i

Download Pdf Manuals

image

Related Search

Related Contents

LG VENUS User's Manual  accès aux cycles préparatoires EHESP  ステンレス両手鍋のプラスチック製取っ手が使用中に  Linksys LGS105-UK network switch  

Copyright © All rights reserved.
Failed to retrieve file