Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BT PAN full report
#1

[attachment=2418]
BT- PAN
PROJECT REPORT
Submitted by MANU P.K AJU ALIAS J1THESH T.S VISHNU PRASAD R ADARSH SUKUMARAN
ABSTRACT
Bluetooth is one of the standards for wireless communication. Tt is excepted that the number of services provided over Bluetooth links will rapidly increase during the next few years. This puts hard demands on the Bluetooth specification, to preserve the interoperability between services offered from different manufactures. It's the Bluetooth profile specification that states the requirement on a Bluetooth application.
The Graphical User Interface (GUI) of the Hie transfer application is designed like a common FTP application. The requirements of the file transfer application are the ability to browse a remote folder structure and to push and pull tiles. The server decides if the user has read-only or read and write permissions in the shared folders. The server also has the ability to desire which folders a user gets access to.
The file transfer profile depends on several underlying profiles and protocols. Two profiles handle discoverability and connection establishment. The application implemented is a client/server file transfer application. It fulfills all the mandatory requirement of the profile specification. It is really a set of five different programs, three running on the server and two on the client. On each there is a security application, which handles discovery and connection establishment. There is one client and one server application, which handle the communication and file browsing. The fifth application is a tool to configure which tile that should be shared and to whom.
TABLE OF CONTENTS
TITLE PAGE NO
LIST OF TABLES vii
LIST OF FIGURES vii
INTRODUCTION
1.1 ABOUT THE PROJECT FEATURES OF BLUETOOTH
1
1
2
2.1 STRENGTHS 2
2.2 MARKETING ASPECTS 3
2.3 RADIO SPECTRUM 3
2.4 AD-HOC RADIO CONNECTIVITY 4
2.5 NETWORK TOPOLOGIES 4
2.6 BLUETOOTH SECURITY 5
2.7 BLUETOOTH POWER 6
2.8 BLUETOOTH INQUIRY 7
2.9 BLUETOOTH SOFTWARE STACK 8
BLUETOOTH APPLICATIONS 10
SYSTEM ANALYSIS 11
4.1 INTRODUCTION 11
4.2 EXISTING SYSTEM I 1
4.3 PROPOSED SYSTEM 12
4.4 FEATURES OF SOFTWARES 12
4.5 SOFTWARE REQUIREMENTS 13
4.6 11ARDWARE REQUIREMENTS 13
CHAPTER TITLE PAGE NO
5 SYSTEM DESIGN 15
5.1 CHOOSING A TARGET DEVICE 1 5
5.2 CHOOSING A PROTOCOL. 1 8
5.3 PORT NUMBERS 21
5.4 SERVICE DISCOVERY PROTOCOL 23
5.5 COMMUNICATING VIA SOCKETS 27
CODING 27
6.1 RFCOMM SOCKETS 35
TESTING 44
7.1 SYSTEM TESTING 39
7.1.1 UNIT TESTING 40
7.1.2 INTEGRATION TESTING 41
7.1.3 VALIDATION TESTING 41
7.1.4 OUTPUT TESTING 41
CONCLUSION 42
APPENDICES 43
RESUME 45
REFERENCES 46
LIST OF TABLES
TABLE TABLE NAME PAGE
2.1.1 COMPARISON OF BLUETOOTH 2
2.7.1 POWER DISSIPATION 7
6.1 TRANSPORT PROTOCOL 30
6.1.1 QUICK REFERENCE 38
Vll
LIST OF FIGURES
FIGURE FIGURE NAME PAGE
2.5.1 SCATTERNET & P1CONET 5
2.6.1 FREQUENCY CHANNEL 6
2.8.1 CONNECTION PROCEDURE 7
2.9.1 PROTOCOL STACK 9
5.3.1 BLUETOOTH PROTOCOLS 22
5.4.1 CONNECTION ESTABLISHMENT 23
5.4.2 SDP RECORD 24
5.5.1 SOCKET CREATION & CONNECTION 28
Mil
CHAPTER 1 INTRODUCTION
1.1 ABOUT THE PROJECT
Bluetooth is a wireless protocol utilizing short-range communications technology facilitating data transmissions over short distances from fixed and/or mobile devices, creating wireless personal area networks (PANs). The intent behind the development of Bluetooth was the creation of a single digital wireless protocol, capable of connecting multiple devices and overcoming issues arising from synchronization of these devices. Bluetooth provides a way to connect and exchange information between devices such as mobile phones, telephones, laptops, personal computers, printers, GPS receivers, digital cameras, and video game consoles over a secure, globally unlicensed Industrial, Scientific, and Medical (ISM) 2.4 GHz short-range radio frequency bandwidth. The Bluetooth specifications are developed and licensed by the Bluetooth Special Interest Group (SIG). The Bluetooth SIG consists of companies in the areas of telecommunication, computing, networking, and consumer electronics.
The Personal Area Networking Profile describe how two or more Bluetooth enabled devices can form an ad-hoc network and how the same mechanism can be used to access a remote network through a network access point. The profile roles contained in this document are the Network Access Point, Group Ad-hoc Network, and Personal Area Network User. Network access points can be a traditional LAN data access point while Group Ad-hoc Networks represent a set of devices that are only attached to one another.
Project will be presented to respond a need of messaging application over a PAN In a PAN over Bluetooth, the transfer of messages can be needed freely in order to communicate among network members. Moreover, the presenter may want to communicate all of the participants at the same time in a conference or presentation. The goal of the project is to make possible of communicating on a PAN over Bluetooth.
CHAPTER 2 FEATURES OF BLUETOOTH
2.1 STRENGTHS
The following table compares the Bluetooth radio to wireless LAN and infrared. These three technologies are the most commonly used in many of today's wireless applications. Each of them has their own set of advantages and disadvantages, and this makes each of them suitable to certain applications.
BTup.iooth Wireless LAN Intra red
Typical Range Medium HO 'in; Long i 100 ru) Short '1 in i
line of sight No No Yes
Bandwidth 1 M!bps shared 1 1 Mbps shared ] 15 kbps N 4 Mbps dedicated
interference ()!her RE de\ ices (''norRFdevices None
Securit) Less secure U van infrared, Uses page link layer authentication. Still requires application layer security. Insecure unless protected, e.g. VVEP A W'PA encryption Very secure, due to short range and lino* of sight requirement
Power Consui.upti:0'n High. Need- \Q maintain a connection Very high. Needs ro maintain a connection. Low. No constant connection like wireless radios.
( oniponent Cos.i About S20. expected to drop to $5. \hnut S.25.
Less than S2.
Table 2.1.1: Comparison of Bluetooth, wireless LAN and infra-red technologies.
The main features of Bluetooth that makes it suitable for use with our project are:
Minimal hardware dimensions.
Low price of Bluetooth components.
Low power consumption for Bluetooth connections.
Inherent security features.
Medium range.
The low cost and small size of the Bluetooth radios means that it can be integrated into many portable devices cheaply. The products offered from companies in the Bluetooth SIG, such as mobile phones. PDAs etc. creates a huge market potential for Bluetooth devices and their applications.
Low power consumption is especially important in this project because the software system requires the Bluetooth radio on the mobile phones to be turned on all the time. This helps to prolong battery life, which is scarce in mobile phones.
2.2 MARKETING ASPECTS
In the last decades, consumer products such as PCs, laptops, personal digital assistants, cell phones etc have increased in popularity. This is based on the continuous cost and size reduction of these devices. The transfer of information between these devices has been hindered because of the need of cables. Bluetooth provides a solution to this by eliminating the need for cabling. It also provides the means for connecting several units to each other, such as setting up small radio Personal Area Networks between any types of Bluetooth devices.
2.3 RADIO SPECTRUM
Bluetooth operates on the unlicensed 2.4 GHz spectrum. This means that the spectrum is open to the public without the need for licenses, as long as they meet requirements specified by the FCC. Moreover, Bluetooth applications are targeted at consumers who do a lot of traveling. Hence the spectrum on which Bluetooth operates on must be available worldwide. The 2.4 GHz spectrum is free in most countries of the world and thus meets this criteria. The use of this spectrum introduces a lot of interference sources to the Bluetooth radio transmissions. One source of interference is high-powered transmitters such as microwave ovens and lighting devices, which also transmit at the 2.4 GHz band. Another source of interference is co-user interference [3], which comes from other Bluetooth users.
2.4 AD-HOC RADIO CONNECTIVITY
The Bluetooth radio system stands out from other radio systems due to its ad-hoc connectivity. The majority of radio systems used today are based on cellular radio architectures. A mobile network is established on a wired backbone infrastructure, and consists of one or more base stations located in different locations to provide cellular coverage. The mobile terminals then access the network in these coverage areas. Hence there is a clear separation between the base stations and the terminals of such systems.
In contrast, there are no distinctive base stations or terminals in the Bluetooth system, nor are there any differences between radio units. There is no wired infrastructure to support connectivity, and there is no predefined central controller for units to rely on for making interconnections. This means that during the implementation of the system, we would not have to worry about the architecture of the resulting network. This is also important because the Bluetooth-enabled devices will be constantly on the move, resulting in a constantly changing network. The lack of an infrastructure means that the network can accommodate such changes easily.
2.5 NETWORK TOPOLOGIES
Bluetooth devices can be organized into groups of two to eight devices, which together form a piconet. Each piconet will contain at least one master, and all other units participating in the piconet will be slaves. The master of a piconet controls the communications within a piconet.
The number of units in a piconet is deliberately limited to eight (one master, seven slaves) in order to keep a high capacity page link between all the units. It also limits the overhead required for addressing. Note that the master/slave role only lasts for the duration of the piconet. Once the piconet is cancelled, these roles are also cancelled. Any unit can become master or slave. By definition, the unit that establishes the piconet becomes the master.
Two or more piconets can be interconnected to form a scattemet. The connection point between two piconets is a Bluetooth unit that is a member of both piconets. One device can be a master in one piconet, and a slave in another. A device can also be a slave on more than one piconet. but it cannot be a master in more than one piconet. as this willmean that the two are actually one piconet (having a single master).
A o J
f (7)
Piconet B
Piconet C
Figure 2.5.1: Shows a scatternet comprising of three piconets. Two piconets are linked to each other by a node which exists in both piconets.
2.6 BLUETOOTH SECURITY
Security in Bluetooth is provided in three ways:
1. Pseudo-random frequency hopping.
2. Authentication
3. Encryption
Frequency hopping is a spread spectrum technique that was intended for noise resilience. However it is also a good way to prevent eavesdropping, because it is very hard for
an eavesdropper to track the frequency changes of a transmission over a Bluetooth network. The following figure shows how the frequency of a Bluetooth channel can change over time.
frequency
4 .
_ time

Figure 2.6.1: Frequency of a Bluetooth channel changing pseudo-randomly.
2.7 BLUETOOTH POWER CONSUMPTION AND OPERATING MODES
Bluetooth supports four modes of activity in order to save power. In order of decreasing power consumption, the four modes are:
1. Active mode
2. Sniff mode
3. Hold mode
4. Park mode
In this thesis, we are concerned mainly with the active mode and the hold modes, since they correspond mainly with the main procedures of the mobile phone. In active mode, the master and slave communicate with each other on the same channel. This would obviously use the most amount of power. This mode is used when there is data communications between both
master and slaves. In hold mode, there is no active communications between master and slave. The slave merely listens to the channel, to see if it should exit this mode. During this time, the slave is able to scan, page or inquire about devices in the same area. This mode consumes significantly less power than the active mode, as noted in the following table.
Modes of Activity
Product I'o..'..er U.i ;*ipation in Park Mode. ['.iv'.er Dissipation to Actiw Mode
( NR Bkkvorc 01 OJ mW 0.6 I ,*5 mW
Table 2.7.1: Comparison of the differences in power dissipation in the two modes of activity.
2.8 BLUETOOTH INQUIRY AND CONNECTION ESTABLISHMENT
Mastci
Slave
Inuuii \
Paee
1 \tLV Scan

Sla\c Response

Connection ( oniK'vlhHl

The inquiry procedure is an important part of Bluetooth, it is a process where one Bluetooth device tries to find all neighbouring Bluetooth devices. A device that is trying to scan for other devices is said to be in "inquiry mode". The device .that listens for an inquire
request is in "inquiry scan mode'. This "inquiry scan mode' is usually set in an Bluetooth device by setting it to be "discoverable". When inquiry is initiated, the device goes into 'inquiry mode" and accelerates its hopping frequency. On the other hand, the device in the 'inquiry scan mode" reduces its hopping frequency. This algorithm will allow the inquirer to catch up with the transmit frequency of devices that is in "inquiry scan mode'. This is important because of the frequency hopping algorithm employed in Bluetooth.
When the frequencies coincide, the scanned device will act as slave and send its address and clock information to the master. After inquiry, the inquirer will be able to initiate connection to the inquired device. Since the connection is initiated by the inquirer, it will act as the master. This initial connection is called paging. Paging is done by the master by sending paging requests to possible slave frequency slots. This frequency slots are calculated from the Bluetooth address and the clock information received during inquiry.
At the time of connection establishment, the slave will synchronize its timing to that of the master's. Throughout the connection, the master never changes its hopping sequence or phase (current hop slot, determined by the master's clock). In contrast, the slave will have to synchronize with the master's clock all the time.
2.9 BLUETOOTH SOFTWARE STACK.
Bluetooth can be defined as a layered protocol architecture consisting of protocols such as the cable replacement protocol, the telephony protocol, the adopted protocol and the core protocols. The layers are specified to add abstraction and to adapt the Bluetooth technology to other existing protocols.
i H5h\
res
Audi.
I VP
T
i( 1AIM l
;< \i
Baseband
Figure 2.9.1: The Bluetooth Protocol Stack. The core protocols are four protocol layers consisting of:
Baseband. Specifies details of the air interface, including frequency, the use of frequency hopping, modulation scheme, and transmit power. Also specifies the protocol for connection establishment within a piconet, addressing, packet format, order of transmission, timing sequence, power control and channel coding.
Link manager protocol (LMP). Responsible for page link setup between Bluetooth devices and ongoing page link management such as encryption and security. Allows service discovery, which detects other Bluetooth devices when in range.
Logical page link control and adaptation protocol (L2CAP). Adapts upper layer protocols to the baseband layer. It is also responsible for the multiplexing data to upper layer. This is done by assigning a particular PSM (multiplexer number).
Service discovery protocol (SDP). Query devices of possible services available. Does not require a connection to be made.
HCI (Host Controller Interface) sits between the T2CAP and LMP. It is the first interface between programmer and the protocol, allowing access to the hardware capabilities. It is also responsible for the multiplexing data to upper layer.
L2CAP layer, as mentioned above acts as an adaptation layer to the upper layer, but it also allows connectionless data transfer.
RFCOMM layer is a cable communication protocol designed to emulate serial ports.
CHAPTER 3 BLUETOOTH APPLICATIONS
Most of today's Bluetooth applieations can be grouped into several categories, namely
1. Office applications
2. Ad-hoc Networking
3. Access control applications
Office applications often relate to the setting up of a wireless office environment. For example, the keyboard and mouse of a computer are connected to the computer itself via a Bluetooth link, or connecting several computers to a Bluetooth-enabled printer. It also involves the synchronization of information between computers. For example, a business man who travels a lot would write a lot of information on his PDA. When he gets home from work, he will want this information to be added to his laptop computer. This can be done easily using if both his PDA and his laptop computer are Bluetooth-enabled. Ad-hoc networking involves several devices in range, forming a community of networks (Personal Area Networks) that only exists as long as it is required.
Current applications include the exchange of electronic business cards between users. Bluetooth devices can be used in access control applications. One application is that it can be for mobile payment, like a credit card. A Bluetooth device such as a Bluetoothenabled mobile phone could communicate with a Bluetooth-enabled cinema ticketing machine, for example, allowing the user to purchase a ticket without queuing, and then billing the appropriate amount to his phone bill. Alternatively, each Bluetooth device could contain a unique code which is used to identify a particular user, and how much credit he has in his credit account. Bluetooth can also be used as an access card. A user can access controlled areas of a building, or certain resources, by just being there, without having to swipe his/her card in a swipe machine.
CHAPTER 4 SYSTEM ANALYSIS
4.1 INTRODUCTION
System analysis is the process of gathering and interpreting facts, diagnosing problems and using the information to recommend improvements on the system. System analysis is a problem solving activity that requires intensive communication between the system users and system developers.
System analysis or study is an important phase of any system development process. The system is studied to the minutest detail and analyzed. The system analyst plays the role of an interrogator and dwells deep into the working of the present system. The system is viewed as a whole and the inputs to the system are identified. The outputs from the organization are traced through the various processing that the inputs phase through in the organization.
A detailed study of these processes must be made by various techniques like Interviews, Questionnaires etc. The data collected by these sources must be scrutinized to arrive to a conclusion. The conclusion is an understanding of how the system functions. This system is called the existing system. Now, the existing system is subjected to close study and the problem areas are identified. The designer now functions as a problem solver and tries to sort out the difficulties that the enterprise faces. The solutions are given as a proposal. The proposal is then weighed with the existing system analytically and the best one is selected. The proposal is presented to the user for an endorsement by the user. The proposal is reviewed on user request and suitable changes are made. This loop ends as soon as the user is satisfied with the proposal.
4.2 EXISTING SYSTEM
A personal area network (PAN) is a computer network used for communication among computer devices (including telephones and personal digital assistants) close to one person. The devices may or may not belong to the person in question. The reach of a PAN is typically a few meters. PANs can be used for communication among the personal devices themselves (intrapersonal communication), or for connecting to a higher level network and the Internet (an uplink). Personal area networks may be wired with computer buses such as USB and Fire Wire.
4.3 PROPOSED SYSTEM
Bluetooth Personal Area Network (Bluetooth PAN) provides wireless connections by enabling links between mobile computers, mobile phones, portable handheld devices, and connectivity to the Internet. Bluetooth PAN is maintained by Bluetooth.
Enhance the current PAN and Connection Manager to include Bluetooth PAN support. This will include
The ability for the Bluetooth pairing wizard to detect PAN functionality.
The ability for the user to select PAN for internet access. Currently, connection types are Packet Data. Data Call, and WiFi. PAN would be added to this.
Adding seamless connection scripts to the Connection Manager so a PAN connection is as easy as a DUN or WiFi connection.
4.4 FEATURES OF SOFTWARF.S
VISUAL STUDIO 2008
ClickOnce improvements
Microsoft introduced a simplified way to deploy Windows Forms clients from the web with Visual Studio 2005 called ClickOnce. With 2008. they've improved the experience by allowing deployment through FireFox (previously only IE was supported), better tile associations so your application can be launched by activating a data file, better support for certificate expiration and changing the deployment location without resigning the application and support for Office add-ins and WPF XAML Browser application deployment.
Multi-framework targeting
This release of Visual Studio has a much-needed feature that I wish had been there before - the ability to target multiple versions of .NET. Specifically, you can select your target framework (2.0 SP1, 3.0 or 3.5) and the project types, toolbox, references, intellisense and features will be appropriately set to that version. This selection can occur during project creation - in the project templates dialog or on the project properties dialog. Be aware that selecting .NET Framework 2.0 actually means 2.0 SP1 and not the original .NET 2.0 framework released with Visual Studio 2005.
VS 2008 Multi-Targeting Support
Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run. debug the .NET 2.0. .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.
Nested Master Page Support
Already Visual Studio 2005 supports nested master pages concept with .NET 2.0. but the problem with this Visual Studio 2005 that pages based on nested masters can't be edited using WYSIWYG web designer. But now in VS 2008 you can even edit the nested master pages.
4.5 SOFTWARE REQUIREMENTS
OPERATING SYSTEM BROWSER
SERVER SIDE SCRIPTING CLIENT SIDE SCRIPTING CONNECTION PROTOCOL
WINDOWS XP
INTERNET EXPLORER 6.0 OR ANY HTTP BROWSER VISUAL C++ VISUAL C++
WIRELESS (BLUETOOTH) RFCOMM, L2CAP
4.6 HARDWARE REQUIREMENTS
PROCESSOR CLOCK SPEED SYSTEM BUS RAM HDD
MONITOR KEY BOARD
PENTIUM IV 2 GHZ 32 BIT 128MB 40GB
SVGA COLOR 108 KEYS
BLUETOOTH DONGLE : 1 Mbits/S
MOUSE : PS/2
CHAPTER 5 SYSTEM DESIGN
System design is the solution to the creation of a new system. This phase is composed of several systems. This phase focuses on the detailed implementation of the feasible system. It emphasis on translating design specifications to performance specification. System design has two phases of development logical and physical design.
During logical design phase the analyst describes inputs (sources), outputs (destinations), and procedures (data flows) all in a format that meats the uses requirements. The analyst also specifies the user needs and at a level that virtually determines the information flow into and out of the system and the data resources. Here the logical design is done through data flow diagrams and database design.
The physical design is followed by physical design or coding. Physical design produces the working system by defining the design specifications, which tell the programmers exactly what the candidate system must do. The programmers write the necessary programs that accept input from the user, perform necessary processing on accepted data through call and produce the required report on a hard copy or display it on the screen.
5.1 CHOOSING A TARGET DEVICE
Every Bluetooth chip ever manufactured is imprinted with a globally unique 48-bit address, referred to as the Bluetooth address or device address. This is identical in nature to the Machine Address Code (MAC) address for Ethernet. In fact, both address spaces are managed by the same organization - the IEE Registration Authority. These Bluetooth addresses, assigned at manufacture time, are intended to be unique and remain static for the lifetime of the chip. It conveniently serves as the basic addressing unit in all of Bluetooth programming.
For one Bluetooth device to communicate with another, it must have some way of determining the other device's Bluetooth address. The address is used in all layers of the Bluetooth communication process, from the low-level radio protocols to the higher level application protocols. In contrast, TCP/IP network devices that use Ethernet discard the 48-bit MAC address at higher layers of the communication process and switch to using IP addresses. The principle remains the same however, in that the unique identifying address of the target device must be known in order to communicate with it. The client program may not have advance knowledge of these target addresses. In Internet programming, the user typically knows or supplies a host name, such as kernel.org. which must then be translated to a physical IP address by DNS. In Bluetooth, the user will typically supply some user-friendly name, such as "My Phone." and the client translates this to a numerical address by searching nearby Bluetooth devices and checking the name of each device.
Device Name
Humans do not deal well with 48-bit numbers, such as 0xO0OEED3I)1829 (in much the same way, we do not deal well with numerical IP addresses like 68.15.34.115), and so Bluetooth devices will almost always have a userfriendly name (also called the display name). This name is usually shown to the user in lieu of the Bluetooth address to identify a device, but ultimately it is the Bluetooth address that is used in actual communication. For many machines, such as mobile cell phones and desktop computers, this name is configurable and the user can choose an arbitrary word or phrase. There is no requirement for the user to choose a unique name, which can sometimes cause confusion when many nearby devices have the same name. When sending a file to someone's phone, for example, the user may be faced with the task of choosing from five different phones, each of which is named "My Phone."
Names in Bluetooth are similar to DNS names in that both are human-friendly identifiers that eventually get translated to machine-friendly identifiers. They differ in that DNS names are unique (there can only be one google.com) and registered with a central database, whereas Bluetooth names are more or less arbitrary, frequently duplicated, and are registered only on the device itself. In TCP/IP, one begins with a DNS name. Translating a DNS name to an IP address involves contacting a nameserver, issuing a query, and waiting for a result. In Bluetooth, the lookup process is reversed. First, a device searches for nearby Bluetooth devices and compiles a list of their addresses. Then, it contacts each nearby device 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 out what's nearby, broadcast a ""discovery" message and wait for replies. Each reply consists of the address of the responding device and an integer identifying the general class of the device (e.g., cell phone, desktop PC. headset, etc.). More detailed information, such as the name of a device, can then be obtained by contacting each device individually.
In practice, this is often a confusing and irritating subject for Bluetooth developers and users. The source of this aggravation stems from the fact that it can take a long time to detect nearby Bluetooth devices. To be specific, given a Bluetooth cell phone and a Bluetooth laptop sitting next to each other on a desk, it will usually take an average of 5 seconds before the phone detects the presence of the laptop, and it sometimes can take upward of 10-15 seconds. This might not seem like that much time, but put in context it is surprising. During the device discovery process, the phone is changing frequencies more than a thousand times a second, and there are only 79 possible frequencies on which it can transmit. It is a wonder why they don't find each other in the blink of an eye. The technical reasons for this are mostly due to the result of a strangely designed search algorithm .
Discoverability and Connectability
For privacy and power concerns, all Bluetooth devices have two options that determine whether or not the device responds to device inquiries and connection attempts. The Inquiry Scan option controls the former, and the Page Scan option controls the latter. Although the names inquiry scan and page scan are confusing, it is important not to confuse these two terms with the actual processes of detecting and connecting to other devices. The reasoning behind these names is that these options control whether the local device scans for device inquiries and connection attempts. A device is in discoverable mode when inquiry scan is on.
5.2 CHOOSING A TRANSPORT PROTOCOL
Different applications have different needs, hence the reason for different transport protocols. This section describes the ones you should know about for Bluetooth programming, and why your application might use them.
The two factors that distinguish the protocols here are guarantees and semantics. The guarantees of a protocol state how hard it tries to deliver a packet sent by the application. A reliable protocol, like TCP. takes the "deliver-or-die" mentality: it ensures that all sent packets get delivered, or dies trying (terminates the connection). A best-effort protocol, like UDP, makes a reasonable attempt at delivering transmitted packets, but ignores the case when the packets do not arrive, say, due to signal noise, a crashed router, an act of god. and so on. The semantics of a protocol can be either packet-based or streams-based. A packet-based protocol like UDP sends data in individual datagrams of fixed maximum length. A streams-based protcol, like TCP, on the other hand, just sends data without worrying about where one packet ends and the next one starts. This choice is more a matter of preference than any specific requirements, because with a little arm-twisting, a packet-based protocol canbe used like streams-based protocol, and vice versa.
Bluetooth contains many transport protocols, nearly all of which are special purpose. We consider four protocols to be essential, although only two, RFCOMM and L2CAP. are likely to be used to get started. And of these two. only the first. RFCOMM, will be relevant for many readers. The protocols are presented in the order of their relevance; the anxious reader can skim over the latter two or three.
RFCOMM
The Radio Frequency Communications (RFCOMM) protocol is a reliable streams-based protocol. It provides roughly the same service and reliability guarantees as TCP. The Bluetooth specification states that it was designed to emulate RS-232 serial ports (to make it easier for manufacturers to add Bluetooth capabilities to their existing serial port devices), but we prefer to turn that definition around and say that RFCOMM is a general-purpose transport protocol that happens to work we'll for emulating serial ports.
The choice of port numbers is the biggest difference between TCP and RFCOMM from a network programmer's perspective. Whereas TCP supports up to 65.535 open ports on a single machine, RFCOMM allows only 30. This has a significant impact on bow to choose port numbers for server applications.
A distinguishing attribute of RFCOMM is that, depending on the application and the target platform, sometimes it is the only choice. Some environments, such as the Microsoft Windows XP Bluetooth API and Nokia Series 60 Python, support only the RFCOMM transport protocol. This really isn't all that bad because it's a robust general-purpose protocol, but it is something worth keeping inmind if you were to consider the other protocols mentioned.
L2CAP
The Logical Link Control and Adaption Protocol (L2CAP) is a packet-based protocol that can be configured with varying levels of reliability. The default maximum packet size is 672 bytes, but this can be negotiated up to 65,535 bytes after a connection is established.
L2CAP can be compared with UDP. which is a best-effort packet-based protocol, but there are enough differences that the use cases for L2CAP are much broader than the use cases for UDP. Both are packet-based protocols, but L2CAP enforces delivery order. In UDP, it is possible for a computer to transmit two packets and have the second packet arrive before the first, due to quirks in Internet routing. This never happens in L2CAP. and packets are always delivered in the order they were sent. Additionally, UDP is restricted to best-effort guarantees, whereas L2CAP can be configured for varying levels of reliability. These differences mean that L2CAP can often be used where UDP would be used, for simple best-effort packet-based communication, but it can also be used for applications where UDP would not be suitable.
Reliability is achieved by a transmit/acknowledgment scheme in which unacknowledged packets may or may not be retransmitted. There are three possible retransmit policies:
never retransmit (but make a best effort):
always retransmit until success or total connection failure (reliable, the default); and
drop a packet and move on to queued data if a packet hasn't been acknowledged after a specified time limit (0-1279 ms). This is useful when data must be transmitted in a timely manner (and it assumes a best effort).
These policies often seem useful at first glance, but there are some major pitfalls to watch out for. The first is that adjusting the delivery semantics for a single L2CAP connection to a remote device affects all L2CAP connections to that device. L2CAP connections to other devices are not affected. Second, L2CAP actually serves as the transport protocol for RFCOMM, so every RFCOMM connection is actually encapsulated within an L2CAP connection.
The primary concern is that changing the L2CAP retransmit policy may have much broader consequences than we would expect. If these consequences are acceptable (e.g., no other Bluetooth applications are running on the device, or they are able to deal with the reliability changes) then the retransmit policy can be quite useful.
ACL
The Asynchronous Connection-oriented Logical (ACL) transport protocol is one that you'll probably never use. but is worth mentioning because all L2CAP connections are encapsulated within ACL connections. Since RFCOMM connections are transported within L2CAP connections, they are also encapsulated within ACL connections. Two Bluetooth devices can have at most a single ACL connection between them, which is used to transport all L2CAP and RFCOMM traffic. ACL is similar to IP in that it is a fundamental protocol that is rarely used to directly transport data. Instead, it is almost always used to encapsulate higher level protocol packets.
f- SCO
The last transport protocol that we mention is the Synchronous Connection- Oriented t(SCO) logical transport. This strange beast is a best-effort packetbased protocol that is .exclusively used to transmit voice-quality audio - not just any audio, but voice-quality audio, I at exactly 64 kb/s. It is useless for transmitting CD-quality audio because the transmission rate ' isn't high enough, but it is just right for making phone calls. If you've used a Bluetooth [headset, then your voice data is probably transmitted over an SCO connection. If you've used .Bluetooth headphones to listen to your Bluetooth MP3 player, then the audio is probably transmitted over an L2CAP connection.
SCO packets are not reliable and never retransmitted, but there is a separate quality of service guarantee. An SCO connection is always guaranteed to have a 64 kb/s transmission rate. If other applications and connections on a device are contending for radio time to, say, transmit a file or synchronize a calendar, the SCO connection will be given priority. To ensure that all SCO connections have this guarantee, no Bluetooth device is allowed to have more ;than three active SCO connections. Furthermore, two Bluetooth devices can have at most one SCO connection between them. In practice, you'll seldom see any device with more than one active SCO connection at a time.
Applications transmitting data, regardless of whether they require reliably delivered packets, should almost always use L2CAP connections. SCO should only be used for transmitting voice-quality audio, and never for any other types of data, or even higher quality audio. In fact, the default SCO settings for most devices will not even transmit data packets transparently. Instead, the packets are encoded using the Continuously Variable Slope Delta audio codec. The received packets, once decoded, look nothing like the actual data transmitted, but sound the same. SCO is of interest because of its widespread use with Bluetooth headsets.
5.3 PORT NUMBERS
A port is used to allow multiple applications on the same device to simultaneously utilize the same transport protocol. Almost all Internet transport protocols in common usage are designed with the notion of port numbers. Bluetooth is no exception, but uses slightly different terminology. In L2CAP, ports are called Protocol Service Multiplexers (PSM), and can take on oddnumbered values between 1 and 32,767. Don't ask why they have to be odd-numbered values, because you probably won't get a convincing answer. In RFCOMM channels 1-30 are available for use.
Reserved/Well-Known Ports
Many transport protocols are designed with specific applications in mind, and at the very outset of designing the protocol, some of the ports are set aside and reserved for these applications. This set of ports is often referred to as the well-known, or reserved, ports for that protocol. It is expected that custom applications will not use any of the well-known ports, unless they are implementing a standardized service assigned to that port number. For example, in TCP/IP, port 80 is reserved for Web traffic, 23 is used for e-mail, and so on.
Figure 5.3.1 Some of the many Bluetooth Transport Protocols.
Bluetooth is no exception, and L2CAP reserves ports 1-1023 for standardized usage. For example, the Service Discovery Protoco uses port 1, and RFCOMM connections are multiplexed on L2CAP port 3. It turns out that RFCOMM does not have any reserved ports, which may not be that surprising given that it has so few port numbers in the first place.
5.4 SERVICE DISCOVERY PROTOCOL
One of the big questions a client application must answer when establishing an outgoing connection is, which port number is the server listening on If the server is a standardized application that uses one of the well-known port numbers, then the answer is easy. If not, then the traditional approach in Internet programming is to hard-code a port number in both the client and server applications. When it comes time to establish the connection, the server listens on that port, and the client connects to that port. The main disadvantage to this approach is that it is not possible to run two server applications which both use the same port number. Due to the relative youth of TCP/IP and the large number of available port numbers to choose from, this has not yet become a serious issue.
Bluetooth tries to avoid this problem by introducing the SDP. The basic premise is that every Bluetooth device maintains an SDP server listening on a well-known port number. When a server application starts up, it registers a description of itself and a port number with the SDP server on the local device. Then, when a remote client application first connects to the device, it provides a description of the service it's searching for to the SDP server, and the SDP server provides a listing of all services that match. Figure 5.2 illustrates this difference. By using this approach. Bluetooth allows server applications to use dynamically assigned - when a server starts up, it can pick an arbitrary port number that is not being used on the local device, and thus ensure that it is free of port conflicts. By decoupling the actual port used from the application itself. Bluetooth is able to avoid a few of the pitfalls that are a nuisance in Internet programming.
Traditional connect ion establishment Hi r n riect ion establ iil-using SDP i merit
c.T.riecl 1
Ik-lit J**. p-.lt-
si.>p seivei
i H. HI
Figure 5.4.1 Traditional network applications use hard-coded port numbers, whereas most Bluetooth applications use an SDP server.
The description of a service that a server application registers with its SDP server, and that the SDP server transmits to inquiring clients, is referred to as a service record, also an SDP record. In theory, the service record is quite simple; it consists of a list of attribute/value pairs. Hach attribute is a 16-bit integer, and each value can be a basic data type, such as an integer or string, or a list of other data types. In some sense, a service record is essentially adictionary of various entries that describe the service being offered. Figure 5.3 illustrates a service record and a few common attributes. Next to the actual port number listed for a service, possibly the two most important attributes in a service record are the Service ID and the Service Class ID List. These two attributes are most often the ones used by a clientto actually identify the desired service.
Service ID
Although having descriptions of services is nice, the big question that still needs to be answered is. how do clients know which service description is the one they seek The approach taken in Bluetooth is to assign every single service a unique identifier, and make sure that the client already knows the unique ID of the service it's looking for. In other words, rather than assigning a port number at design time, developers assign a unique ID at design time.

ServteelD
ServiceCldsslDList
b ' -
1 IJXjD/O - . ..
Service Name
1 ' Es anipl f : i '
Protocol Ctescriptort.ist:
b..
I ,

Figure 5.4.2 An SDP record is a list of attribute/value pairs, where each entry describes one aspect of the service offered.
The description of a service that a server application registers with its SDP server, and that the SDP server transmits to inquiring clients, is referred to as a service record, also an SDP record. In theory, the service record is quite simple; it consists of a list of attribute/value pairs. Each attribute is a 16-bit integer, and each value can be a basic data type, such as an integer or string, or a list of other data types. In some sense, a service record is essentially adictionary of various entries that describe the service being offered. Figure 5.3 illustrates a service record and a few common attributes. Next to the actual port number listed for a service, possibly the two most important attributes in a service record are the Service ID and the Service Class ID List. These two attributes are most often the ones used by a clientto actually identify the desired service.
Service ID
Although having descriptions of services is nice, the big question that still needs to be answered is, how do clients know which service description is the one they seek The approach taken in Bluetooth is to assign every single service a unique identifier, and make sure that the client already knows the unique ID of the service it's looking for. In other words, rather than assigning a port number at design time, developers assign a unique ID at design time.
. 0.* V' ce Reco
Serv :elD
Sei v cr'TlcisslDList

Serv :=r-tanre
" i xampl i r.f"
Rot: : ^DfescriptorList
' L_
Figure 5.4.2 An SDP record is a list of attribute/value pairs, where each entry describes one aspect of the service offered.
The big advantage that using a unique ID has over using port numbers is that the space of valid unique IDs is designed to be much larger than the space of valid port numbers, allowing developers to minimize the chance of unique ID conflicts.
This approach has been done before, and the Internet Engineering Task Force has a standard method for developers to independently come up with their own 128-bit Universally Unique Identifiers (UUID). This is the basic idea around which SDP revolves, and this identifier is called the service's Service ID. Specifically, a developer chooses this UUID at design time and when the program is run, it registers a service record containing its Service ID with the SDP server for that device. A client application trying to find a specific service would query the SDP server on each device it finds to see if the device offers any services with that same UUID. The standard notation for a UUID is a hyphen-separated series of digits of the form "XX-XX-XX-XX-XX", where each "X" is a hexadecimal digit. The first segment of eight digits corresponds to bits 1-32 of the UUID. the next segment of four digits is bits 33-36, and so on.
Service Class ID List
Although a Service ID by itself can take us a pretty long way in terms of identifying services and finding the one we want, it's really meant for custom applications built by a single development team. The Bluetooth designers wanted to distinguish between these custom applications and classes of applications that all do the same thing. For example, two different companies might both release Bluetooth software that provides audio services over Bluetooth. Even though they're completely different programs written by different people, they both do the same thing. To handle this, Bluetooth introduces a second UUID, called the Service Class ID. Now, the two different programs can just advertise the same Service Class ID. and all will be well in Bluetooth Land. Of course, this is useful only if the two companies agree on which Service Class ID to use.
Another thought to consider is this: What if 1 have a single application that can provide multiple services For example, many Bluetooth headsets can function as a simple headphone and speaker, and advertise that service class; but they are also capable of controlling a phone call - answering an incoming call, muting the microphone, hanging up. and so on. Although it's possible to just register two separate services in this case, each with a specific service class, the Bluetooth designers chose to allow every service to have a list of service classes that the service provides. So while a single service can have only one Service ID, it can have many Service Class IDs.
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. The lower 96 bits of all reserved Bluetooth UUIDs are the same, so they are typically referred to by their upper 16 or 32 bits.
To get the full 128-bit UUID from a 16-bit or 32-bit number, take the Bluetooth Base UUID (00000000-0000-1000-8000-00805F9B34FB) and replace the leftmost segment with the 16-bit or 32-bit value. Mathematically, this is the same as 128 bit UUID = 16 or 32 bit number . 296 + Bluetooth Base UUID
Common SDP Attributes
Bluetooth defines several reserved attribute IDs that always have a special meaning, and the rest can be used arbitrarily. Some of the more common reserved attributes are Service Class ID List: A list of service class UUIDs that the service provides. This is the only mandatory attribute that must always appear in a service record. Service ID: A single UUID identifying the specific service. Service Name: A text string containing the name of the service. Service Description: A text string describing the service provided. Protocol Descriptor List: A list of protocols and port numbers used by the service. Profile Descriptor List: A list of Bluetooth profile descriptor that the service complies with. Bluetooth Profiles are described. Each descriptor consists of a UUID and a version number. Service Record Handle: A single unsigned integer that uniquely identifies the record within the device.
SDP Record Structure
The basic building block of an SDP record is the data element. A data element is composed of a type, a size, and a value. The type of a data element can be either a basic type, such as integers and strings, or a sequence of data elements. The size indicates how much space the value takes up (in bytes), and the value is just the actual data to convey. When we say that an SDP record is a list of attributes, we actually mean that every service record is a single data element with type sequence. The data elements within this sequence always alternate between 16-bit unsigned integers (the attribute) and some other type (the value) that varies with the attribute. For example, the type of the data element corresponding to the service name is always a string, but the service ID will be of type UUID.
5.5 COMMUNICATING VIA SOCKETS
Given the address of a device, the transport protocol, and the port, Bluetooth programming is essentially the tried and true network programmer's friend: sockets. A server application waiting for an incoming Bluetooth connection is conceptually the same as a server application waiting for an incoming Internet connection, and a client application attempting to establish an outbound connection behaves the same whether it is using RFCOMM, L2CAP, TCP. or UDP. For this reason, extending the socket programming framework to encompass Bluetooth is a natural approach. This section gives a brief introduction to the essential concepts behind socket programming without any distracting code.
Introducing the Socket A socket in network programming represents the endpoint of a communication link. The idea is that from a software application's point of view, all data passing through the page link must go into or come out of the socket. First used in the 4.2BSD operating system, sockets have since become the de facto standard for network programming. There are two general ways to use a socket - as either a client or a server, (Figure 5.6). As before, the words client and server only refer to whether the socket is used to create outgoing connections, or accept incoming connections. Just because a socket is used as a server socket doesn't actually mean that the application itself is a traditional ""server" application, connections.
livnt
Client
[" unci Server
'"iinfcting Client
I i'.l.Tlill'l V-IY>'
nn- r..i :.-pt
Figure 5.5.1 A conceptual illustration of the steps needed to obtain a connected socket. (1) When a socket is first created, it is mostly useless. (2) Binding a socket attaches it to a local Bluetooth adapter and port number. (3) When a server socket is placed in listening mode, then remote devices can initiate the connection procedure. (4) After a server socket has accepted a new connection, it spawns a new socket that is connected to the remote device.
Just because a socket is used as a server socket doesn't actually mean that the application itself" is a traditional "server" application. The first step an application must take is to create a socket. Since sockets are used for many types of communication, the create command typically specifies the transport protocol to use. In Bluetooth programming, we'll almost always be creating either L2CAP or RFCOMM sockets.
Client Sockets
Client sockets are fairly simple in that once the socket has been created, only one additional step needs to be taken to obtain a connected socket. This is to issue a connect command, specifying the address and port of the target device. The operating system then takes care of all the lower level details, reserving resources on the local Bluetooth adapter, searching
for the remote device, forming a piconet, and establishing a connection. Once the socket is connected, it can be used for data transfer.
Server/Listening Sockets
Server sockets are a bit more involved when it comes to obtaining a connected socket. Three steps must be taken: First, the application must hind the socket to local Bluetooth resources, specifying the local Bluetooth adapter and the port number to use. Second, the listen command is used to place the socket into listening mode. This instructs the operating system to accept incoming connection requests on the local adapter and port number the socket was bound to. Finally, the accept command is used to obtain a connected socket that can be used for data transfer.
One of the major differences between a server socket and a client socket is that the server socket first created by the application can never be used for actual communication. Instead, each time the server socket accepts a new incoming connection using the accept command, it spawns a brand new socket that represents the newly established connection. The server socket then goes back to listening for more connection requests, and the application should use the newly created socket to communicate with the client.
Communicating Using a Connected Socket
Once a Bluetooth application has a connected socket, using it for communication is simple. The send and receive commands are used to . . . well, send and receive data. A send pushes out the bytes, but its successful return only means that the bytes have been moved from the application address space to the operating system's buffers. They may or may not have actually left the device. A receive returns at least some data. It blocks until data, even 1 byte, are arrived. The receive will return with 0 bytes only when the connection is broken. When the application is finished, it simply invokes the close command to disconnect the socket. Closing a listening server socket unbinds the port and stops accepting incoming connections.
CHAPTER 6 CODING
The essentials of Bluetooth programming under Microsoft Windows XP follow the general trend, although there are complications. With the introduction of Service Pack 1. Microsoft began natively supporting Bluetooth in Windows XP. Many devices are now natively supported, and can be programmed using the Platform SDK, which is available for download from the Microsoft web site. Prior to this native support, many Bluetooth stacks were developed for the Windows environment. One of the more popular Bluetooth development environments was. and still is. the Widcomm Bluetooth SDK., fable 6.1 illustrates the transport protocols supported by the Microsoft andWidcomm Bluetooth development kits. In addition to the protocols listed. theWidcomm development kit also provides support for OBEX (object exchange), printing, DUN. and A2DP.
Microsoft RFCOMM
Widcomm; Brcedcom RFCOMM CAP SCO HCI
Table 6.1 Transport protocols supported by the Microsoft and Widcomm stacks.
Although the Microsoft Bluetooth stack is limited, it does have the advantage of coming standard with Windows XP SP2. This chapter shows how to program with the Microsoft Bluetooth API. It does not cover how to set up a development environment, since doing so is already described in many other places. We assume that the interested reader already has a working installation of Microsoft Visual C++ and the Microsoft Windows XP Platform SDK.
Header Files and Linked Libraries
Three header files are needed to enable use of the Bluetooth extensions. The following must be included and in this order: winsock2.li, ws2bth.h. and BluetoothAPIs.h. The program should be linked against ws2 32.lib and irprops.lib. These files are all included with the
Windows Platform SDK.
Initializing the Windows Sockets API
As with all programs using the Windows Sockets 2 API. some initialization code is required before the use of any socket functions. Programs should deline and invoke something similar to the following function before using any Bluetooth resources:
#inelude <winsock2 . h> #include <ws2bth . h> void initialize windows sockets ( ) / WSADATA wsaData ;
WORD wYersionRcquested = MAKEWORD( 2, 0 ); if( WSAStartup( wVersionRequested. &wsaData ) !=NO ERROR ) { fprintf(stderr , "Error initializing window sockets!\n" ); ExitProcess ( 2 );
This needs to be invoked only once per process. Once a program is finished using Bluetooth resources, it should call WSACleanup to release resources used by the Windows Sockets 2 API: int WSACTeanup(void );
Representing Bluetooth Addresses
The Microsoft Bluetooth API represents a Bluetooth address as a 64-bit unsigned integer. There is a dedicated datatype, BTH ADDR. defined as typedef ELONGLONG BTHADDR ;
Although this representation takes up more space than the required 48 bits, using a basic data type, rather than a composite structure or array, is convenient. To convert a BTH ADDR into a human-readable string, it should be wrapped inside a SOCKADDR BTH data structure, and then passed to WSAAddressTnString. Similarly. WSAStringToAddress is used to convert string representations of Bluetooth addresses into SOCKADDR BTH structs which have the BTH ADDR representation as an internal field:
INT WSAAddressToString ( LPSOCKADDR IpsaAddress . DWORD dwAddressLength .
LPWSAPROTOC OLINFO IpProtocolInfo . L.PTST.R IpszAddressString
LPDVVORD lpdwAddressStringLength ); INT WSAStringToAddress ( LPTSTR AddressString . INT AddressFamily ,
LPWSAPROTOCOLINFO IpProtocolInfo . LPSOCKADDR IpAddress .
LPINT lpAddressLength );
The function WSAAddressToString takes five parameters. The first is a pointer to a SOCKADDR BTH. cast as a pointer to a SOCKADDR. Its addressFamily field should be AF BTH. and its btAddr field should be the Bluetooth address being converted. The second parameter is always sizeof(SOCKADDR BTH). The third parameter is always NULL, while the last two are the address and size of a string buffer, respectively. When the function returns, the string buffer is filled with a human-readable version of the specified address. The function WSAStringToAddress also takes five parameters. The first three are the string buffer, AF BTH, and NULL. The last two parameters are a pointer to a SOCKADDR BTH cast as a pointer to a SOCKADDR. and a pointer to an integer whose value is sizeof( SOCKADDR BIT! ). If the string is in the proper format of "XX:XX:XX:XX:XX:XX"\ then upon return, the address structure is populated with the specified Bluetooth address.
Starting a Device Inquiry
To start the device discovery process for detecting nearby Bluetooth devices, use the WSALookupServiceBegin Junction:
int WSALookupServiceBegin ( WSAQUERYSET* queryset. DWORD dwControlFlags . HANDLE* IphLookup ):
The parameter queryset points to a valid WSAQUERYSET data structure, and is initially used to specify that a Bluetooth device discovery is desired. The WSAQUERYSET
structure has quite a few fields, but only two of them matter for a device inquiry.
queryset->dwSize should always be set to sizeof(WSAQUERYSET). and queryset->dwNameSpace should always be set toNS BTH. All other fields should be initialized to 0. lphLookup is an output parameter that should initially point to an unused HANDLE. After the function returns successfully, lphLookup is used with other functions to refer to the ongoing device discovery process. dwControlFlags specifies the exact details of the device discovery, and is a combination (bitwise OR) of the following flags:
LLP CONTAINERS is always specified for device discoveries.
LUP FLUSHCACHE flushes the cache of previously detected devices. If not specified, then devices detected in previous device discoveries may also be returned in the current one.
LUP RETURN TYPE causes the Bluetooth device class to be retrieved. Device classes are described in the Bluetooth Assigned Numbers document. This field can be useful for doing things like displaying a different type of icon for each type of detected device (e.g., cell phones, printers, and computers), bthdcf.h has a number of macros useful for parsing this field.
LUP RETURN NAME indicates that the function also attempts to determine the user-friendly name of each detected device.
LUP RETURN ADDR retrieves the Bluetooth address of each detected device. You almost certainly want to specify this.
Parsing Device Inquiry Results
WSALookupServiceBegin only initiates the device discovery, and doesn't return any information about nearby devices. To find out which devices were actually detected, use WSALookupServieeNext. Each call to this function retrieves details for at most one device (possibly none), so it should be called repeatedlv until there are no more devices left to detect:
int WSALookupServiceNext( HANDLE hLookup . DWORD dwControlFlags . DWORD* lpdwBufferLength , WSAQUERYSET* queryset);
The first two parameters are related to the call to WSALookupServiceBegin. hLookup and dwControlFlags should be the handle created by and the flags passed to WSALookupServiceBegin. respectively. lpdwBufferLength should point to a DWORD containing the size, in bytes, of the queryset. This is also used as an output parameter in special cases, described shortly. Finally, queryset is an output parameter that should point to a valid WSAQUERYSET structure. It could (but doesn't have to) be the same structure that was passed to WSALookupServiceBegin. When WSALookupServ iceNext completes successfully, the following fields of queryset will lake meaning:
IpszServicelnstanceName: If the LUP RETURN NAME flag was specified, this points to a character string containing the user-friendly name of the device.
lpServiceClassld: If LUP RETURN TYPE was specified, this points to a GU1.D structure whose Datal field contains the device class of the detected device.
IpcsaBuffer: If LUP RETURN ADDR was specified, this points to a CSADDR INFO
structure, whose RemoteAddr field contains a SOCKET ADDRESS structure, whose IpSockaddr field points to a SOCKADDR BTH structure, whose btAddr field is a BTH ADDR representing the address of the detected device.
Occasionally, WSALookupServiceNext will fail and return an error code of WSAEFAULT. This just indicates that queryset isn*t large enough to hold the information about the detected device. In this case. lpdwBufferLength will be filled in with the size needed to hold everything. Simply reallocate a new pointer with at least that amount of space and issue anew call to WSALookupServiceNext.
Finishing a Device Discovery
When all the detected devices have been reported. WSALookupServiceNext will fail with an error code of WSA E NO MORE. The program should then end the inquiry with a call to WSALookupServiceEnd and continue:
int WSALookupServ iceEndl HANDLE hLookup ):
This function simply releases the resources used during the device discovery process. It should be passed the same handle used in the other two functions.
6.1 RFCOMM SOCKETS
Microsoft follows the same socket programming conventions used in other APIs and programming languages, including the same functions for creating, connecting, and transferring data with sockets. The socket addressing data structure and the integer constants, however, are unique. Following standard procedure, use the socket function to allocate a Bluetooth socket:
SOCKET socket( int af, int type , int protocol);
Since the Microsoft Bluetooth API supports only RFCOMM sockets, the three parameters to this function will always be AF BTH, SOCK STREAM, and BTHPROTO RFCOMM
Addressing Structure
Next, a SOCKADDR BTH is filled in to specify the details of either which device to connect to (for client applications) or which RFCOMM port to listen on (for server applications):
typedef struct SOCKADDR BTH /
USHORT addressFamily :
BTH-A DDR btAddr ;
GUID serviceClassId ;
ULONC port :
/ SOCKAI)I)R BTH ;
The fust field. addressFamily. should always be AF
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Powered By MyBB, © 2002-2024 iAndrew & Melroy van den Berg.