PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 This page intentionally left blank PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers This book provides an introduction to Bluetooth programming, with a specific focus on developing real code. The authors discuss the major concepts and techniques involved in Bluetooth programming, with special emphasis on how they relate to other networking technologies. They provide specific descriptions and examples for creating applications in a number of programming languages and environments, including Python, C, Java, GNU/Linux, Windows XP, Symbian Series 60, and Mac OS X. No previous experience with Bluetooth is assumed, and the material is suitable for anyone with some programming background. The book places special emphasis on the Python language examples, showing the translation of concepts and techniques into actual working programs. Programmers who have never seen or used Python before will find these examples easy to follow and understand. Albert S. Huang is a PhD candidate at MIT’s Computer Science and Artificial Intelligence Laboratory (CSAIL). His primary areas of research are robotics and computer vision. Larry Rudolph, PhD, received his doctorate from NYU’s Courant Institute. He is currently a Principal Research Scientist at MIT and a cofaculty member at the New England Complex Science Institute. His most recent research has been in the field of mobile computing. PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Albert S. Huang and Larry Rudolph Massachusetts Institute of Technology CAMBRIDGE UNIVERSITY PRESS Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São Paulo Cambridge University Press The Edinburgh Building, Cambridge CB2 8RU, UK Published in the United States of America by Cambridge University Press, New York www.cambridge.org Information on this title: www.cambridge.org/9780521703758 © Albert S. Huang, and Larry Rudolph 2007 This publication is in copyright. Subject to statutory exception and to the provision of relevant collective licensing agreements, no reproduction of any part may take place without the written permission of Cambridge University Press. First published in print format 2007 eBook (NetLibrary) ISBN-13 978-0-511-35583-7 ISBN-10 0-511-35583-1 eBook (NetLibrary) ISBN-13 ISBN-10 paperback 978-0-521-70375-8 paperback 0-521-70375-1 Cambridge University Press has no responsibility for the persistence or accuracy of urls for external or third-party internet websites referred to in this publication, and does not guarantee that any content on such websites is, or will remain, accurate or appropriate. PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Contents Preface r Introduction page vi r Bluetooth Programming with Python 41 r C Programming with GNU/Linux 67 r C Programming with Microsoft Windows XP 111 r Java–JSR 82 137 r Other Platforms and Environments 157 r Bluetooth Tools in Linux 181 Index 193 V PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Preface About This Book This book provides an introduction to Bluetooth wireless technology∗ and Bluetooth programming, with a specific focus on the parts of Bluetooth that concern a software developer. While there is already a host of existing literature about Bluetooth, few of these texts are written for the programmer who is concerned primarily with creating Bluetooth software applications. Instead, they tell all about Bluetooth, when most of the time, the programmer is interested only in a tiny fraction of this information. This book purposefully and happily leaves out a great deal of information about Bluetooth. Concepts are simplified and described in ways that make sense to a programmer, not necessarily the ways they’re laid out in the Bluetooth specification. The approach is to start simply, allowing the reader to quickly master the basic concepts with the default parameters before addressing a few advanced features. Despite these omissions, this book is a rigorous introduction to Bluetooth, albeit with a narrow focus. Applications can be developed without an understanding of the radio modulation techniques or the algorithms underlying the generation of Bluetooth encryption keys. Programmers, however, ∗ Throughout this book, we will abbreviate the phrase “Bluetooth wireless technology” with the concise word “Bluetooth.” VI PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Preface need to understand issues such as the available transport protocols, the processes governing establishing connections, and the mechanisms for transferring data. We strongly believe in learning by example and have included working programs that demonstrate the concepts and techniques introduced in the text.∗ Examples are provided for a wide variety of programming languages and environments, including Python, C, and Java, running on GNU/Linux, Windows, Nokia Series 60, and OS X. Special emphasis is given to the Python language examples – the simplicity and clarity of Python allows us to very easily show the translation of concepts and techniques into actual working programs. We believe that programmers who have never seen or used Python will find these examples easy to follow and understand. This book is not meant to be a be-all and end-all guide to Bluetooth programming; rather it is meant to serve as a stepping stone, the first foothold for programmers interested in working with Bluetooth. The exposition of concepts and demonstration of techniques should be sufficient to allow any programmer to start creating his or her own functional Bluetooth applications that can interoperate with many other Bluetooth devices. For those interested in a deeper understanding of the inner workings and nitty-gritty details of Bluetooth, this book serves as sufficient preparation to enable one to tackle the more complex and technical documents like the Bluetooth specification itself. Audience This book targets the computer programmer looking for an introduction to Bluetooth and how to program with it. It assumes no previous knowledge of Bluetooth (you may have never even heard of it before picking up this book), but does assume that you have some programming experience and have access to and can use either a GNU/Linux, Windows XP, or OS X development environment. Because Bluetooth programming shares much in common with network programming, there will be frequent references and comparisons to concepts in network programming, such as sockets and the TCP/IP transport protocols. A basic understanding of these concepts will help solidify your understanding ∗ Visit our Web site to download the examples in the book. Check updates, errata, and new material: www.btessentials.com or www.cambridge.org/9780521703758. VII PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Preface of Bluetooth programming, but the text is written such that it does not assume the reader has this knowledge. Organization of This Book Chapter provides an introduction to Bluetooth and the essentials of Bluetooth programming. The first chapter is divided into two major sections. The first section can be considered the bare essentials, most of which must be understood in order to create a functional Bluetooth program. The second section is material that is highly relevant to the Bluetooth programmer, but is not of critical importance when creating simple Bluetooth programs. Chapter shows how the concepts and techniques introduced in Chapter can be implemented in the Python programming language using the PyBluez extension module. The simplest examples (Device Discovery, Service Search, and RFCOMM) work on both GNU/Linux and Windows XP SP2 computers, and a few examples require a GNU/Linux computer. This chapter allows the programmer to quickly and easily create fully functional Bluetooth programs with minimal effort. Chapter describes in detail how to create Bluetooth applications targeted for the GNU/Linux operating system. Programming examples are given in C, and require the BlueZ stack, which is now a part of the standard Linux kernel. Device Discovery, Service Search, RFCOMM, L2CAP, HCI, and SCO are described. Chapter describes the current state of Bluetooth programming in Windows XP. A detailed introduction is then given for the Microsoft Bluetooth stack, which comes standard in Windows XP SP2 (and is expected to be present in Windows Vista as well). Examples are given for Device Discovery, Service Search, and RFCOMM. Chapter describes how to create Bluetooth applications using the Java programming language. JSR-82, the standard Java API for Bluetooth programming, is introduced along with examples for Device Discovery, Service Search, RFCOMM, and L2CAP. Chapter provides a partial introduction to Bluetooth programming on the Nokia Series 60 and OS X operating systems. The Series 60 Python Bluetooth API is described with examples for Device Discovery, Service Search, and RFCOMM. Device Discovery and outgoing RFCOMM connections using the OS X Objective C Bluetooth API are introduced with examples. Lastly, Bluetooth serial ports are introduced as an alternative to standard VIII PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Tools GNU/Linux where is usually hci0. (hci1 specificies the second Bluetooth adapter if you have two, hci2 is the third, etc.) Most of the commands require superuser privileges. Some of the most useful ways to use this tool are presented below. The command that the user types into the Linux shell is prefaced by the hash (#) prompt. This is usually followed by the output of the system. Display the Status of Recognized Bluetooth Adapters The most basic usage, without parameters or commands, simply supplies information: # hciconfig hci0 : Type : USB BD Address : 00:0F : D : : : ACL MTU : 192:8 SCO MTU : 64:8 UP RUNNING PSCAN ISCAN RX bytes:505075 acl : sco : events:5991 errors : TX bytes:25758 acl : sco : commands:1998 errors : Each Bluetooth adapter recognized by BlueZ is displayed here. In this specific case, there is only one adapter, hci0, and it has Bluetooth Address 00:0F:3D:05:75:26. The “UP RUNNING” part on the second line indicates that the adapter is enabled. “PSCAN” and “ISCAN” refer to Inquiry Scan and Page Scan, which are described a few paragraphs down. The rest of the output is mostly statistics and a few device properties. Enable/Disable an Adapter The up and down commands to this tool can be used to enable and disable a Bluetooth adapter: # hciconfig hci0 down # hciconfig hci0 : Type : USB BD Address : 00:0F : D : : : ACL MTU : 192:8 SCO MTU : 64:8 DOWN RX bytes:505335 acl : sco : events:5993 errors : TX bytes:25764 acl : sco : commands:2000 errors : # hciconfig hci0 up # hciconfig hci0 : Type : USB 183 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers BD UP RX TX Address : 00:0F : D : : : ACL MTU : 192:8 SCO MTU : 64:8 RUNNING PSCAN ISCAN bytes:505075 acl : sco : events:5991 errors : bytes:25758 acl : sco : commands:1998 errors : Display and Change the User-Friendly Name of an Adapter The name command is fairly straightforward, and can be used to display and change the user-friendly name of the Bluetooth adapter: # hciconfig hci0 name hci0 : Type : USB BD Address : 00:0F : D : : : ACL MTU : 192:8 SCO MTU : 64:8 Name : ’ Trogdor ’ # hciconfig hci0 name ’StrongBad’ # hciconfig hci0 name hci0 : Type : USB BD Address : 00:0F : D : : : ACL MTU : 192:8 SCO MTU : 64:8 Name : ’ StrongBad ’ Configure Inquiry Scan and Page Scan The inquiry scan and page scan settings for a Bluetooth adapter determine whether it is detectable by nearby Bluetooth devices and whether it will accept incoming connection requests, respectively. The following table summarizes which commands to use when configuring these two options: Inquiry Scan Page Scan Command On Off On Off On On Off Off piscan pscan iscan noscan For example, the following invocation disables both Inquiry Scan and Page Scan for the first Bluetooth adapter: # hciconfig hci0 noscan 184 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Tools GNU/Linux hciconfig Summary There are many more ways to use hciconfig, all of which are described in the help text (hciconfig -h) and the manpages (man hciconfig). It is the tool to use for any nonconnection-related settings for a Bluetooth adapter. Finally, note that changes made by hciconfig are only temporary, and the effects are erased after a reboot or when the device is disabled and enabled again. The recommended way to ensure that a configuration option is always set is to modify /etc/bluetooth/hcid.conf. This file is typically loaded on system start-up, and is used to configure each Bluetooth adapter attached to the system. The formatting, syntax, and usage of this file is well documented in the hcid.conf manpage. 7.2 hcitool The tool hcitool has two main uses. The first is to search for and detect nearby Bluetooth devices, and the second is to test and show information about low-level Bluetooth connections. In a sense, hcitool picks up where hciconfig ends – once the Bluetooth adapter starts communicating with other Bluetooth devices. Detecting nearby Bluetooth Devices hcitool scan searches for nearby Bluetooth devices and displays their addresses and user-friendly names: # hcitool scan Scanning . . . 00:11:22:33:44:55 AA : BB : CC : DD : EE : FF : : : : : AB 0 : : : B0 : B : Cell Phone Computer−0 Laptop Nokia 6600 In this invocation, four Bluetooth devices were found. Detecting the addresses of nearby Bluetooth devices and looking up their user-friendly names are actually two separate processes, and conducting the name lookup can often take quite a long time. If the user-friendly name is not needed, then hcitool inq is useful for performing only the first part of the search, finding the addresses of nearby devices. 185 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Testing Low-Level Bluetooth Connections The tool hcitool can be used to create piconets of Bluetooth devices and show information about locally connected piconets. When writing Bluetooth software, we won’t have to worry about these low-level details, just like we won’t have to worry about instructing the Bluetooth adapter on which radio frequencies to use. For application programming, this part of hcitool is strictly of educational use, because BlueZ automatically takes care of piconet formation and configuration in the process of establishing higher level (RFCOMM) and (L2CAP) connections. For the reader who is curious about using it for basic piconet configuration, the hcitool cc and hcitool commands are the first places to start. hcitool cc forms a piconet with another device, and is fairly straightforward to use. For example, to join a piconet with the device 00:11:22:33:44:55, # hcitool cc 00:11:22:33:44:55:66 hcitool can then be used to show information about existing piconets. # hcitool Connections : < ACL 0 : 1 : 2 : 3 : 4 : 5 handle 47 state lm MASTER Here, the output of hcitool indicates that the local Bluetooth adapter is the master of one piconet, and the device 00:11:22:33:44:55 is a part of that piconet. For details on the rest of the output, see the hcitool documentation. Note: A fairly common mistake is to try to use hcitool to create data transport connections between two Bluetooth devices. It’s important to know that even if two devices are part of the same piconet, a higher level connection needs to be established before any application-level data can be exchanged. Creating the piconet is only the first step in the communication process. When writing code, as shown in the preceding chapters, this is not needed. 7.3 sdptool The tool sdptool has two uses. The first is for searching and browsing the Service Discovery Protocol (SDP) services advertised by nearby devices. This 186 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Tools GNU/Linux is useful for seeing what Bluetooth profiles are implemented by another Bluetooth device, such as a cellular phone or a headset. The second is for basic configuration of the SDP services offered by the local machine. Browsing and Searching for Services sdptool browse [addr] retrieves a list of services offered by the Bluetooth device with address addr. Omitting addr causes sdptool to check all nearby devices. If local is used for the address, then the local SDP server is checked instead. Each service record found is then briefly described. A typical service record might look like this: # sdptool browse 00:11:22:33:44:55 Browsing 0 : 1 : 2 : 3 : 4 : 5 Service Name : Bluetooth Serial Port Service RecHandle : 0x10000 Service Class ID List : "Serial Port " (0x1101 ) Protocol Descriptor List : "L2CAP" (0x0100 ) "RFCOMM " (0x0003 ) Channel : Language Base Attr List : code ISO639 : 0x656e ¯ encoding : 0x6a base offset : 0x100 ¯ Profile Descriptor List : "Serial Port " (0x1101 ) Version : 0x0100 Here, the device 00:11:22:33:44:55 is advertising a single service called “Bluetooth Serial Port” that’s operating on RFCOMM channel 1. The service has the Universally Unique Identifier (UUID) 0x1101, and also adheres to the Bluetooth Serial Port Profile, as indicated by the profile descriptor listed at the bottom. In general, this information is sufficient for an application to determine whether or not this is the service that it’s looking for (has UUID 0x1101), and how to connect to it (use RFCOMM channel 1). sdptool search can be used to search nearby devices for a specific service. The service to search for can be specified either as a UUID or as a preset string 187 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers such as “SP” (Serial Port) or “OPUSH” (OBEX Object Push). To obtain a full list of the preset strings, invoke sdptool -h. For example, to search for services advertising the Serial Port UUID invoke # sdptool search SP Alternatively, to search directly on its UUID # sdptool search 0x1101 Basic Service Configuration can be used to advertise a set of predefined services, all of which are standardized Bluetooth Profiles. It cannot be used to advertise an arbitrary service with a user-defined UUID; this must be done programmatically. This means it won’t be very useful for advertising a custom service. sdptool del can be used to unadvertise a local service. The SDP server maintains a handle for each service that identifies it to the server, essentially a pointer to the service record. To find the handle, just look at the description of the service using sdptool browse and look for the line that says “Service RecHandle:”. Using the example above, the Serial Port service has the handle 0x10000, so on that machine, issue the following command to stop advertising the service: sdptool add # sdptool del 0x10000 sdptool also provides commands for modifying service records (e.g., to change a UUID), which you could actually use, but probably don’t want to. These, along with the add and del commands, exist so that programmers can look at the source code of sdptool for examples on how to the same in their own applications. 7.4 hcidump For low-level debugging of connection setup and data transfer, hcidump can be used to intercept and display all Bluetooth packets sent and received by the local machine. This can be very useful for determining how and why a connection fails, and let us examine at exactly what stage in the connection process communications failed. hcidump requires superuser privileges. When run without any arguments, hcidump displays summaries of Bluetooth packets exchanged between the local computer and the Bluetooth adapter as they appear. This includes packets on device configuration, device 188 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Tools GNU/Linux inquiries, connection establishment, and raw data. Incoming packets are preceded with the “>” (greater than) symbol, and outgoing packets are preceded with the “ HCI Event : Command Status (0x0f ) plen > HCI Event : Inquiry Result (0x02 ) plen 15 > HCI Event : Inquiry Complete (0x01 ) plen Here, we can see that one command (Inquiry) was sent out instructing the Bluetooth adapter to search for nearby devices, and three packets of size 5, 4, and 15 bytes were received: information on the status of the command, an inquiry result indicating that a nearby device was detected, and another status packet once the inquiry completed. Notice that used this way, hcidump provides only basic summaries of the packets, which is not always enough for debugging. One option is to use the -X flag, which causes hcidump to display the raw contents of every packet in hexadecimal format along with their ASCII decodings. Used in the above example, we might see the following: # hcidump -X HCI sniffer − Bluetooth packet analyzer ver 1.23 device : hci0 snap len : 1028 filter : 0xffffffff ¯ < HCI Command : Inquiry (0x01 | x0001 ) plen 0000: 33 8b 9e 08 00 > HCI Event : Command Status (0x0f ) plen 0000: 00 01 01 04 > HCI Event : Inquiry Result (0x02 ) plen 15 0000: 01 26 75 05 3d 0f 00 01 02 00 00 01 3e d6 1f > HCI Event : Inquiry Complete (0x01 ) plen 0000: 00 .&u . = . . . . . . . > . . . Okay, so unless you’ve memorized the Bluetooth specification and can decode the raw binary packets in your head, maybe that’s not as useful as we’d like. While hcidump -X is great for very low level debugging of raw packets, the -V option is a nice compromise. hcidump -V displays as much information as it can gather from each packet, and summarizes the ones it can’t interpret. If used together with -X, it still provides all the information for packets that 189 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers it can decode, but also shows the raw hexadecimal data for all the other packets. (These tend to be application-level data packets.) Repeating our example once again, we might see this: # hcidump -X -V HCI sniffer − Bluetooth packet analyzer ver 1.23 device : hci0 snap len : 1028 filter : 0xffffffff ¯ < HCI Command : Inquiry (0x01 | x0001 ) plen lap 0x9e8b33 len num > HCI Event : Command Status (0x0f ) plen Inquiry (0x01 | x0001 ) status 0x00 ncmd > HCI Event : Inquiry Result (0x02 ) plen 15 bdaddr 00:0F : D : : : mode clkoffset 0x1fd5 class 0x3e0100 > HCI Event : Inquiry Complete (0x01 ) plen status 0x00 Now, the packets decoded according to the Bluetooth specification can be seen, which are probably mostly meaningless to you right now, but would make sense if you found the need to read the parts of the Bluetooth specification on device inquiry. Since this is a simple example, hcidump is able to fully decode each packet, so there is no raw hexadecimal data. As with the other utilities, there are many more ways to use hcidump for debugging and low-level display of Bluetooth packet communication that you can find by reading the help text included with BlueZ. 7.5 l2ping The tool l2ping sends echo packets to another Bluetooth device and waits for a response. An echo packet is a special type of L2CAP packet that contains no meaningful data; when a Bluetooth device receives an echo packet, it should just send (echo) the packet back to the originator. This is useful for testing and analyzing L2CAP communications with another Bluetooth device. If two devices are communicating, but seem a little sluggish, then l2ping can provide timing information on how long it takes to send and receive packets of a certain size. The only required parameter is the address of the Bluetooth device to “ping.” For example, to send echo packets to the device 01:23:45:67:89:AB:, # l2ping -c 01:23:45:67:89:AB Ping : : : : : : AB from 0 : D0 : F5 : 0 : E : B5 ( data size 44) . . . 190 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Tools GNU/Linux 44 44 44 44 44 bytes bytes bytes bytes bytes from from from from from : : : : : AB : : : : : AB : : : : : AB : : : : : AB : : : : : AB id id id id id time time time time time 60.87ms 55.97ms 50.96ms 51.94ms 48.93ms continues sending packets until stopped by pressing Ctrl-C. Other command-line arguments let us control the size of the packets sent, the delay between packets, how many to send, and so on. For details on how to use these capabilities, invoke l2ping -h. l2ping 7.6 uuidgen As the name suggests, uuidgen generates UUIDs that, for all intents and purposes, can be considered unique from all other UUIDs. This is most useful when designing new Bluetooth applications that make use of SDP to advertise a nonstandard UUID (e.g., a new Service Class ID). To use this tool, simply invoke it and record the generated number. For example, # uuidgen 30c007a7−7792−49e7−a266−60426e757f18 7.7 Summary The GNU/Linux user-level tools for Bluetooth development are highlighted in this chapter because of their value in debugging and understanding a Bluetooth application. Since Bluetooth deals with multiple device communicating wirelessly, these tools are useful not only for debugging an application written for the GNU/Linux platform but also for verifying that applications written on other platforms appear and behave as expected. Often, an application will fail unexpectedly, or it may not operate as hoped with a new device. In the best case, a few simple steps, such as an sdptool browse to verify that a service record is properly advertised or an hcitool scan to verify that a device is discoverable, may resolve the problem. For more difficult bugs, hcidump can (and often will) be used to analyze the raw packets being transmitted over a Bluetooth connection to determine exactly where in the communications process the problem lies. 191 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Index 802.11, 2, 27 A2DP. See Advanced Audio Distribution Profile, 33 accept, 25, 45–47, 61, 75, 78, 80, 82, 101, 107, 108, 122, 125, 161, 162 acceptAndOpen, 149, 153, 154 ACL, 12 adapter, adaptive frequency hopping, 29 addressFamily, 121 Advanced Audio Distribution Profile, 33 advertise service, 53, 55 AF BTH, 118, 121 AF BLUETOOTH, 75, 76 ba2str, 69, 70, 75, 80 bdaddr t, 70 BDADDR ANY, 75 big-endian, 82 bind, 46, 47, 52, 53, 61, 75, 78, 80, 82, 85, 107, 108, 122, 124, 161–163 Bluetooth, address, 6, 70, 117, 143, 160, 169 Assigned Numbers, 72 device name, 73 limitations, 34 profile, 32 range, 26 speed, 27 Bluetooth Base UUID, 20 Bluetooth Specifications, BluetoothDeviceAddress, 169 BluetoothError, 48 BluetoothSocket, 45–47, 49, 53, 60–63 BlueZ, 67 Broadcom, 111 bt advertise service, 164 bt discover, 159, 160 BT PORT ANY, 122 bt rfcomm get available server channel, 163 bt advertise service, 162 bt discover, 160, 162 bt error, 106 bt rfcomm get available server channel, 161 btAddr, 120, 121 BTH ADDR, 120 btohl, 83 193 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Index btohs, 83 BTPROTO RFCOMM, 75, 76 byte, 151, 155 byte order, 82 C programming language, 67 CFRunLoop, 165, 168 channel, 14 class of device, 72, 143 Client–Server, close, 45, 47, 61, 62, 69, 75, 76, 79, 81, 82, 101, 106, 123, 151, 155, 161 closeChannel, 171 closesocket, 123, 125, 128 connect, 25, 45–47, 56, 57, 62, 64, 76–80, 82, 100, 107, 108, 122, 161, 162 connectable, Connection, 139 connection client, incoming, outgoing, server, connection, 139 ConnectionHandler, 170 Connector.open, 149, 150 Connector.open(), 154 Continuously Variable Slope Delta, 13 CSADDR INFO, 120 data element, 21 Data1, 120 device, address, discovery, device discovery, 35 GNU/Linux, 71 Java, 140 Microsoft API, 116 OS X, 165 Series 60 Python, 159 device inquiry, device discovered, 58, 59 deviceDiscovered, 142, 143 194 DeviceDiscoverer, 58, 59 deviceInquiryComplete, 166, 167 deviceInquiryDeviceFound, 166, 167 Dial-Up Networking Profile, 33 discover devices, 43, 44 discover devices(), 44 discoverable, Discoverer, 166, 167 DiscoveryAgent, 140, 142, 144 DiscoveryListener, 140, 142–145 display name, DNS, DWORD, 119 EDR. See Enhanced Data Rate, 27 Enhanced Data Rate, 27 Ethernet, 2, event loop, 24 Extended Inquiry Response, fcntl, 99–101 FD ISSET, 102 FD SET, 102 FD ZERO, 102 FD ISSET, 102 FD SET, 101 FD ZERO, 101 File Transfer, 32 find devices, 58, 59 find service, 54 find devices, 58 flush timeout, 11, 104 FormatMessage, 114 free, 87, 106 getAttributeValue, 146 getBluetoothAddress, 140, 143 getConnectionURL, 141, 146, 154 getDiscoveryAgent, 141, 142 getFriendlyName, 140, 143 getLocalDevice, 141 getLocalDevice(), 142 getsockname, 52, 53, 85, 122–124 getsockopt, 83, 84, 108 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Index GNU/Linux, 67 GUID, 120 HANDLE, 119 Hands-Free Audio Profile, 33 HCI. See Host Controller Interface, 33 GNU/Linux, 103 hci , 73 hci devid, 70, 72 hci get route, 70, 72, 103 hci inquiry, 71, 72 hci open dev, 59, 71, 72, 103 hci read remote name, 73 hci read voice setting, 108 hci send cmd, 103, 104 hci send req, 60, 103, 104, 108 hci send request, 104, 105, 107 hci write local name, 104 hci write voice setting, 108 hci devid, 70 hci get route, 69, 73 hci inquiry, 69, 72 hci open dev, 61, 69, 71, 106 hci read remote name, 69, 73 hci read voice setting, 108 hci send cmd, 103 hci send req, 61, 62, 103, 106 hci write voice setting, 108 hciconfig, 182 hcitool, 186 HID. See Human Interface Device Profile, 33 Host Controller Interface, 33 htobl, 83 htobs, 83, 106 Human Interface Device Profile, 33 InputStream, 151 inquiry scan, 8, 36 inquiry complete, 58 inquiryComplete, 142, 143 inquiryCompleted, 141, 144 interlaced inquiry scan, 37 IOBluetoothDevice, 169, 170 IOBluetoothDeviceInquiry, 166, 167 IOBluetoothDeviceInquiryDelegate, 167 IOBluetoothNSStringToDeviceAddress, 169 IOBluetoothRFCOMMChannel, 168–170 IOBluetoothRFCOMMChannelDelegate, 170 ioctl, 105–107 IOError, 52 IOException, 150, 151, 154 IP, 12 JABWT, 137 Java, 137 Java Community Process, 137 L2CAP, 11 GNU/Linux, 79 Java, 151 L2CAPConnection, 139, 153–155 L2CAPConnectionNotifier, 139, 152, 153 l2ping, 190 libbluetooth, 67 link key, 31 Linux, 67 listen, 45, 46, 61, 75, 78, 80, 122, 161, 162 little-endian, 82 LocalDevice, 140, 142 lookup name, 43, 44 lookup name(), 44 lpSockaddr, 120 LUP CONTAINERS, 119 LUP FLUSHCACHE, 119 LUP RETURN ADDR, 119, 120 LUP RETURN NAME, 119, 120 LUP RETURN TYPE, 119, 120 MAC, master, 29 maximum transmission unit GNU/Linux, 83 Microsoft Bluetooth stack, 42 MTU, 83 195 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Index NS BTH, 118 NSApplicationMain, 165 NSAutoreleasePool, 165, 168 NULL, 118 OBEX, 32 Opcode Command Field, 59, 103 Opcode Group Field, 59, 103 openInputStream, 147, 150 openOutputStream, 150 openRFCOMMChannelAsync, 169, 170 OS X, 164 OutputStream, 151 page scan, pairing, 30 PAN. See Personal Area Network Profile, 33 Personal Area Network Profile, 33 piconet, 29 PIN, 30 port, 14 dynamically assigned, 85, 122, 139, 163 dynamically asssigned, 16 reserved, 14 well-known, 14 port, 121 pre inquiry, 58 process event, 59 Profile Descriptor List, 20, 98 programming asynchronous, 24, 99 Bluetooth, Internet, synchronous, 24 TCP/IP, Protocol Descriptor List, 20 Protocol Service Multiplexer, 14 PSM. See Protocol Service Multiplexer, 14 PyBluez, 41 Python, 158 radio frequencies, 27 read, 151 receive, 25, 153–155 196 recordlen, 131 recv, 45, 47, 48, 61, 73, 75, 79, 81, 103, 123, 125, 161–163, 170 RemoteAddr, 120 RemoteDevice, 143 Request for Comments, 32 RFC. See Request for Comments, 32 RFCOMM, 10 GNU/Linux, 74 Java, 146 Microsoft API, 120 OS X, 168 serial ports, 171 Series 60 Python, 161 rfcommChannelData, 170 rfcommChannelOpenComplete, 170 RS-232, 10 scatternet, 30 SCO, 12 GNU/Linux, 107 SDP. See Service Discovery Protocol, 16 SDP record, 17, 21 sdp close, 93 sdp connect, 93, 96 sdp data alloc, 87 sdp get access protos, 97, 98 sdp get proto port, 97, 98 sdp get service classes, 97 sdp list append, 87, 91 sdp list free, 87 sdp record register, 93 sdp record t, 86 sdp service search attr req, 97 sdp set access protos, 92 sdp set info attr, 92 sdp set profile descs, 91 sdp set service classes, 91 sdp set service id, 91 sdp uuid128 create, 86, 91, 96 sdp uuid16 create, 86, 91, 96 sdp uuid32 create, 86, 96 sdp attr add, 87 sdp close, 90 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Index sdp connect, 90, 93, 95, 96 sdp data alloc, 87, 89 sdp data free, 87 sdp get access protos, 95, 97 sdp get profile descs, 98 sdp get proto port, 95, 97 sdp get provider name, 99 sdp get service classes, 98 sdp get service desc, 99 sdp get service id, 98 sdp get service name, 98 sdp list append, 89, 91, 95 sdp list free, 90, 95 sdp record free, 95 sdp record register, 90, 93 sdp service search attr req, 95, 97 sdp set access protos, 89, 92 sdp set browse groups, 89, 92 sdp set info attr, 89, 92 sdp set profile descs, 89, 91 sdp set service classes, 89, 91 sdp set service id, 91 sdp uuid128 create, 86, 89, 91 sdp uuid16 create, 86, 91 sdp uuid32 create, 86 SDPGetPort, 126, 128 sdptool, 186 searchServices, 144–146 security mode, 31 select, 24 select, 24, 25, 55, 57, 58, 99–103 send, 25, 45, 47, 62, 73, 76, 79, 82, 102, 103, 108, 123, 128, 153, 155, 161–163 Serial Port Profile, 33 serial ports, 171 Series 60, 158 service advertisement GNU/Linux, 88 Java, 146 Microsoft API, 129, 130 Series 60 Python, 164 Service Class ID List, 17, 19 Service Class List, 98 Service Description, 20, 98 Service ID, 17, 98 Service Name, 20, 98 Service Provider, 98 service record, 17 Service Record Handle, 20 service search GNU/Linux, 93 Java, 144 Microsoft API, 133 Series 60 Python, 159 serviceClassId, 121 ServiceRecord, 146, 149, 150, 154 services, 162 servicesDiscovered, 141, 143, 145, 146, 150 serviceSearchCompleted, 143, 145 set l2cap mtu, 49 set packet timeout, 50 set security, 163 set security, 162 setblocking, 56 setDelegate, 166 setsockopt, 83, 84 shared secret, 30 silen, 131 Simple Pairing, 32 slaves, 29 SOCKADDR, 118, 121 SOCKADDR BTH, 118, 120, 121, 123 socket, 21 blocking, 24 client, 23 listening, 23 non-blocking, 24 server, 23 socket, 73, 76, 77, 80, 81, 100, 107, 121, 122, 124, 127, 161, 162 SOCKET ADDRESS, 120 SOCKET ERROR, 114 SPP. See Serial Port Profile, 33 stack, 37 start, 167 startInquiry, 140–143 stop advertising, 53, 54 197 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Index str2ba, 70, 76, 82, 95, 100, 107 StreamConnection, 139, 147, 149–151, 155 StreamConnectionNotifier, 139, 147, 149 strerror, 73 Symbian, 158 TCP, TCP/IP, timeout, 102 transport protocol, best-effort, 9, 104 guarantees, packet-based, 10 reliable, 9, 104 semantics, streams-based, 10 UDP, 9, 11 unicode, 164 USB, user-friendly name, UUID, 18 reserved, 19 short, 19 UUID, 152 198 Visual Studio, 113 Voice-over-IP, Widcomm, 111 Windows Sockets API, 113 Windows XP, 111 withAddress, 169 withChannelID, 169 write, 108, 151, 170 writeAsync, 170 writeSync, 168, 170 WSAAddressToString, 117, 118, 125, 133 WSACleanup, 114, 117 WSAGetLastError, 114, 117 WSALookupServiceBegin, 116, 118, 119, 126, 133, 134 WSALookupServiceEnd, 117, 120, 127, 134 WSALookupServiceNext, 117, 119, 120, 126, 133, 134 WSAQUERYSET, 118, 119 WSASetService, 125, 128–130, 132 WSAStartup, 114, 116, 124, 127 WSAStringToAddress, 118, 127 [...]... individually and queries it for its user-friendly name Searching for Nearby Devices Device discovery, also known as device inquiry, is the process of searching for and detecting nearby Bluetooth devices It is simple in theory: To figure 7 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers out what’s nearby, broadcast a “discovery” message and wait for replies Each reply... 18, 2007 8:41 Preface Bluetooth programming Bluetooth programming using RFCOMM serial ports is described along with its merits and drawbacks Examples are given for GNU/Linux, Windows XP, and OS X Chapter 7 introduces a series of GNU/Linux Bluetooth development tools that are indispensable for the serious Bluetooth developer Although these tools are built only for the GNU/Linux operating system, Bluetooth. .. fact, combined with the first, means that changing ∗ This is accurate for all intents and purposes, but is not technically correct See the next section (ACL) for details 11 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers the delivery guarantees for L2CAP also changes the delivery guarantees for RFCOMM The primary concern is that changing the L2CAP retransmit... numbers in the first place This information is summarized in Table 1.2 14 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Introduction ACL L2CAP RFCOMM RFCOMM L2CAP L2CAP SCO Figure 1.3 Some of the many Bluetooth Transport Protocols 15 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Table 1.2 Port numbers and their terminology for various protocols Since... CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers that are given folksy names, often refer to something very specific and with a narrow scope For example, there is no single specification of the Internet Rather each of the components has its own specification Ethernet, for example, describes how to connect a bunch of machines together to form a simple network, but that’s... to remember, but most Bluetooth implementations don’t actually enforce this requirement Bluetooth Reserved UUIDs Similar to the way L2CAP and TCP have reserved port numbers for special purposes, Bluetooth also has reserved UUIDs Occasionally referred to as short UUIDs, these are mostly used for identifying predefined service classes, but also for transport protocols and profiles (Bluetooth profiles are... profiles are described in Section 1.3.6.) The lower 96 bits of all reserved Bluetooth UUIDs are the 19 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Table 1.3 Example of reserved Bluetooth UUIDs To obtain the full 128-bit UUID from a reserved UUID, shift it left by 96 bits and add the Bluetooth Base UUID SDP RFCOMM L2CAP SDP Server Service Class Serial Port... specifically for voice-quality audio, and unless you’re transmitting exactly that, you should probably stick with either RFCOMM or L2CAP 13 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Figure 1.3 illustrates the relationships between the major transport protocols A connection is represented by a box, and a box within another box indicates that packets for the... send( ), recv( ) close( ) Figure 1.2 There are also five major conecptual steps for programming an incoming connection As with outgoing connections, the details of Internet and Bluetooth programming are related, although slightly different 5 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers The seasoned network programmer will notice that some of the steps... Understanding Bluetooth as a Software Developer There is nothing especially difficult about Bluetooth, although the unusually wide scope of Bluetooth makes it hard to get started There is so much in the Bluetooth specification and at so many different levels, it is hard to distinguish the essentials from the elective Technology specifications, especially ones ∗ http://www .bluetooth. com /Bluetooth/ Learn/Technology/Specifications/ . July 18, 2007 8:41 This page intentionally left blank PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers This book provides an introduction to Bluetooth. computing. PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 PAB CUNY993C-Huang 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Albert S. Huang and Larry Rudolph Massachusetts. 978-0-521-70375-8 July 18, 2007 8:41 Bluetooth Essentials for Programmers Choose a target device Choose a transport protocol and port number Establish a connection Transfer data Disconnect Search for nearby devices