CLI339CLI339Building Bluetooth Building Bluetooth Applications On The Applications On The Windows CE 5.0 And Windows CE 5.0 And Windows Mobile PlatformsWindows Mobile Platforms
Anil DhawanAnil DhawanProgram ManagerProgram ManagerWindows MobileWindows Mobile
MManagementanagementTToolsools
CCommunicationsommunications& & MMessagingessaging
Device Update Agent
Software Update Services
Live Communications Server
Exchange Server
Internet Security and Acceleration Server
Speech Server
Image Update
LLocation ocation SServiceservices
MMultimediaultimedia
MapPoint
DirectX
Windows Media
Visual Studio 2005DDevelopment evelopment TToolsools
Win32
MFC 8.0, ATL 8.0
NNativeative
MManagedanaged
SServer erver SSideide
LLightweightightweight
RRelationalelationalSQL Server 2005 Express EditionEDB
DDa
taata
PPro
gra
mm
ing
ro
gra
mm
ing
MM
od
el
od
el
DDevice evice BBuilding uilding TToolsools
HHardware/ardware/DDriversrivers
Windows XP DDK
Windows Embedded Studio
Platform Builder
OEM/IHV SuppliedBSP
(ARM, SH4, MIPS)OEM Hardware and Standard Drivers
Standard PC Hardware and Drivers
SQL Server 2005SQL Server 2005 Mobile Edition
ASP.NET Mobile Controls ASP.NET
.NET Compact Framework .NET Framework
Microsoft Operations Manager
Systems Management Server
AgendaAgenda
Technology OverviewTechnology Overview
Bluetooth Application ConceptsBluetooth Application Concepts
Windows CE DevelopmentWindows CE Development
Windows Mobile DevelopmentWindows Mobile Development
DemoDemo
Q&AQ&A
Technology OverviewTechnology Overview
A short range wireless communication A short range wireless communication technologytechnology
10-100 meter range10-100 meter range
Operates in 2.4 GHz band using frequency hoppingOperates in 2.4 GHz band using frequency hopping
Ad-Hoc network topologyAd-Hoc network topology
Supports voice and data through separate Supports voice and data through separate channelschannels
Support for device discoverySupport for device discovery
Devices can be queried for capabilitiesDevices can be queried for capabilities
Standardized servicesStandardized services
Typical Usage ScenariosTypical Usage Scenarios
Audio ServicesAudio ServicesHands Free devicesHands Free devices
Wireless Stereo HeadsetsWireless Stereo Headsets
Wireless Data servicesWireless Data servicesShare Internet ConnectionsShare Internet Connections
Ad-Hoc Data ExchangeAd-Hoc Data Exchange
Business card transferBusiness card transfer
File exchangeFile exchange
PrintingPrinting
Cable ReplacementCable ReplacementKeyboard, Mouse, PrinterKeyboard, Mouse, Printer
AgendaAgenda
Technology OverviewTechnology Overview
Bluetooth Application ConceptsBluetooth Application Concepts
Windows CE DevelopmentWindows CE Development
Windows Mobile DevelopmentWindows Mobile Development
DemoDemo
Q&AQ&A
Bluetooth DevicesBluetooth Devices
Identified by unique addressIdentified by unique address
Advertise to others in discoverable Advertise to others in discoverable modemode
Class of device fieldClass of device field
Devices maintain list of supported Devices maintain list of supported servicesservices
Use Service Discovery for querying list on Use Service Discovery for querying list on other devicesother devices
Bluetooth ServicesBluetooth Services
Describe data exchange protocolsDescribe data exchange protocolsIdentified by a unique GUIDIdentified by a unique GUID
Standardized services called “profiles” Standardized services called “profiles” for common use casesfor common use cases
File Transfer (FTP)File Transfer (FTP)
Dial-Up networking (DUN)Dial-Up networking (DUN)
Stereo Audio (A2DP)Stereo Audio (A2DP)
General TipsGeneral Tips
Keep users informedKeep users informedUse OS UI for device discovery, pairingUse OS UI for device discovery, pairing
Application should handle latencyApplication should handle latency
Don’t block UI threadsDon’t block UI threads
Handle errors gracefullyHandle errors gracefully
Conserve the juiceConserve the juiceLimit time in discoverable modeLimit time in discoverable mode
Keep Bluetooth Off when not in useKeep Bluetooth Off when not in use
5 step process for application 5 step process for application developmentdevelopment
The 5 Step ProcessThe 5 Step Process
Find devices in rangeFind devices in range
Choose a device to connect withChoose a device to connect with
Establish a secure connection (pairing)Establish a secure connection (pairing)
Choose a serviceChoose a service
Transfer DataTransfer Data
Step 1: Find Devices In RangeStep 1: Find Devices In Range
Target devices must Target devices must be in discoverable modebe in discoverable mode
Client device listens to broadcasts Client device listens to broadcasts from discoverable devicesfrom discoverable devices
Step 2: Choose A Device Step 2: Choose A Device To Connect WithTo Connect With
OS usually provides GUI to connect OS usually provides GUI to connect with another devicewith another device
Each device identified by a unique Each device identified by a unique addressaddress
Step 3: Establish A Secure Step 3: Establish A Secure Connection Connection
Process called “pairing”Process called “pairing”
Requires both end points to use the Requires both end points to use the same pin keysame pin key
Usually part of connecting UIUsually part of connecting UI
Step 4: Choose A ServiceStep 4: Choose A Service
Each service identified by unique GUIDEach service identified by unique GUID
Set of “standard” services for well-Set of “standard” services for well-known profilesknown profiles
New applications can publish own New applications can publish own GUIDGUID
Services usually chosen through Services usually chosen through device UIdevice UI
Step 5: Transfer DataStep 5: Transfer Data
Point to point style 2-way Point to point style 2-way communicationcommunication
Applications use service/profile Applications use service/profile protocols to communicate effectivelyprotocols to communicate effectively
AgendaAgenda
Technology OverviewTechnology Overview
Bluetooth Application ConceptsBluetooth Application Concepts
Windows CE DevelopmentWindows CE Development
Windows Mobile DevelopmentWindows Mobile Development
DemoDemo
Q&AQ&A
Bluetooth Application Bluetooth Application ProgrammingProgramming
Winsock API is extended to support Winsock API is extended to support BluetoothBluetooth
New Protocol Family for Bluetooth New Protocol Family for Bluetooth
AF_BTHAF_BTH
New Protocol Option New Protocol Option
BTPROTO_RFCOMMBTPROTO_RFCOMM
New socket options for BluetoothNew socket options for BluetoothEnable/disable encryptionEnable/disable encryption
Control send/receive buffer sizeControl send/receive buffer size
Set power levelSet power level
Windows CE: Windows CE: Native ApproachNative Approach
Windows Sockets APIsWindows Sockets APIsDevice and Service Discovery: Device and Service Discovery: WSALookupServiceBegin(), WSALookupServiceBegin(), WSALookupServiceNext(), WSALookupServiceNext(), WSALookupServiceEnd()WSALookupServiceEnd()
Use standard socket connection APIsUse standard socket connection APIsbind(), listen(), accept(), connect()bind(), listen(), accept(), connect()
Data Transfer APIsData Transfer APIssend(), recv()send(), recv()
Bluetooth Enabling Legacy Bluetooth Enabling Legacy ApplicationsApplications
Useful for applications built around Useful for applications built around interfacing with serial devicesinterfacing with serial devices
GPS receivers, barcode scanners, etc.GPS receivers, barcode scanners, etc.
Virtual serial ports expose Bluetooth Virtual serial ports expose Bluetooth link as a COM portlink as a COM port
Legacy application remains untouchedLegacy application remains untouched
Limited number of COM ports available Limited number of COM ports available on deviceon device
AgendaAgenda
Technology OverviewTechnology Overview
Bluetooth Application ConceptsBluetooth Application Concepts
Windows CE DevelopmentWindows CE Development
Windows Mobile DevelopmentWindows Mobile Development
DemoDemo
Q&AQ&A
Bluetooth Application Bluetooth Application Development On Windows MobileDevelopment On Windows Mobile
NativeNativeCan leverage WinCE Winsock APIsCan leverage WinCE Winsock APIs
Windows Mobile specific utility methodsWindows Mobile specific utility methodsBthGetMode()/BthSetMode()BthGetMode()/BthSetMode()
Managed CodeManaged CodeBluetooth Class LibraryBluetooth Class Library
Windows Mobile: Windows Mobile: Managed ApproachManaged Approach
Use UI for pairingUse UI for pairing
Publish ServicePublish Servicenew BluetoothService( GUID )new BluetoothService( GUID )
List of Paired DevicesList of Paired DevicesBluetoothRadio.PairedDevicesBluetoothRadio.PairedDevices
Connect to a serviceConnect to a serviceBluetoothDevice.Connect( GUID )BluetoothDevice.Connect( GUID )
Use NetworkStream objects for data transferUse NetworkStream objects for data transfer
Windows Mobile Managed Windows Mobile Managed Approach BenefitsApproach Benefits
SimplicitySimplicityIntuitive class interface for all levels of managed developersIntuitive class interface for all levels of managed developers
Focus on the application, not on the technologyFocus on the application, not on the technology
Easy to build custom servicesEasy to build custom servicesLeverage NETCF APIs for object serializationLeverage NETCF APIs for object serialization
Flexible, high level networking APIsFlexible, high level networking APIsPowerful NetworkStream classPowerful NetworkStream class
Rich threading supportRich threading support
Shared SourceShared SourceAdd and change under the hoodAdd and change under the hood
AgendaAgenda
Technology OverviewTechnology Overview
Bluetooth Application ConceptsBluetooth Application Concepts
Windows CE DevelopmentWindows CE Development
Windows Mobile DevelopmentWindows Mobile Development
DemoDemo
Q&AQ&A
ConclusionConclusion
Bluetooth is a ubiquitous, powerful ad-Bluetooth is a ubiquitous, powerful ad-hoc networking technologyhoc networking technology
Rich support on Windows CE and Rich support on Windows CE and Windows MobileWindows Mobile
Windows Sockets APIWindows Sockets API
Managed Class Library for Windows Managed Class Library for Windows MobileMobile
Leverage Visual Studio 2005 for native Leverage Visual Studio 2005 for native and managed developmentand managed development
While at MEDC 2005…While at MEDC 2005…Fill outFill out an evaluation for this session an evaluation for this session
Randomly selected instant Randomly selected instant WINWIN prizes! prizes!
Use Use real technology in a labreal technology in a lab Instructor led Instructor led Reef E/FReef E/F & & Breakers LBreakers L
Self-paced Self-paced Reef B/CReef B/C
VisitVisit the Microsoft Product Pavilion the Microsoft Product Pavilion
in the Exhibit Hall in the Exhibit Hall Shorelines BShorelines B
After The Conference…After The Conference…
DevelopDevelop
BuildBuild
InstallInstall
BuildBuild
JoinJoin
InstallInstall
EnterEnter
JoinJoin
Full-featured trial versions of Windows CE Full-featured trial versions of Windows CE and/or Windows XP Embeddedand/or Windows XP Embedded
Cool stuff & tell us about it: Cool stuff & tell us about it: msdn.microsoft.com/embedded/community
Windows Embedded Partner Program:Windows Embedded Partner Program:www.mswep.com
Windows Mobile 5.0 Eval Kit including Windows Mobile 5.0 Eval Kit including Visual Studio 2005 Beta 2Visual Studio 2005 Beta 2
Mobile2Market Contest and win up to $25000: Mobile2Market Contest and win up to $25000: mobile2marketcontest.com
Microsoft Solutions Partner Program:Microsoft Solutions Partner Program:partner.microsoft.com
Tools & ResourcesTools & Resources
msdn.microsoft.com/msdn.microsoft.com/ embeddedembedded
microsoft.public.microsoft.public. windowsxp.embeddedwindowsxp.embedded windowsce.platbuilderwindowsce.platbuilder windowsce.embedded.vcwindowsce.embedded.vc
blogs.msdn.com/blogs.msdn.com/ mikehallmikehall
Windows CE 5.0 Eval KitWindows CE 5.0 Eval KitWindows XP Embedded Eval KitWindows XP Embedded Eval Kit
msdn.microsoft.com/msdn.microsoft.com/ mobilitymobility
microsoft.public.microsoft.public. pocketpc.developer pocketpc.developer smartphone.developer smartphone.developer dotnet.framework.compactframeworkdotnet.framework.compactframework
blogs.msdn.com/blogs.msdn.com/ windowsmobilewindowsmobile vsdteamvsdteam netcfteamnetcfteam
Windows Mobile 5.0 Eval KitWindows Mobile 5.0 Eval Kit
WebsitesWebsites
NewsgroupsNewsgroups
BlogsBlogs
ToolsTools
BuildBuild DevelopDevelop
Q&AQ&A
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
AppendixAppendix
Link PropertiesLink PropertiesAsynchronous Connection-Less (ACL)Asynchronous Connection-Less (ACL)
721/57.6 kbps max asymmetric721/57.6 kbps max asymmetric
432.6 kbps max symmetric432.6 kbps max symmetric
Synchronous Connection-Oriented (SCO)Synchronous Connection-Oriented (SCO)Symmetric Point-to-point channelSymmetric Point-to-point channel
Used for voice channelsUsed for voice channels
64 kbps bi-directional data streams64 kbps bi-directional data streams
ACL and SCO can be present in a single ACL and SCO can be present in a single piconetpiconet
Data transmitted in Time Divided SlotsData transmitted in Time Divided Slots
Bluetooth v1.2Bluetooth v1.2
Faster connectionFaster connection
Adaptive frequency hoppingAdaptive frequency hopping
Extended SCO linksExtended SCO links
Scatter modeScatter mode
Enhanced error detection and flow controlEnhanced error detection and flow control
Bluetooth Piconet / ScatternetBluetooth Piconet / ScatternetPiconetPiconet
Master controls piconet, Master controls piconet, hopping sequence and phase hopping sequence and phase
Up to 7 active slavesUp to 7 active slaves
Up to 127 “parked” slavesUp to 127 “parked” slaves
Node must be part of a piconet Node must be part of a piconet to communicateto communicate
Master tells slave when it can Master tells slave when it can transmittransmit
Piconets can chain together Piconets can chain together and form a larger network and form a larger network ( Scatternet )( Scatternet )
MM
SSSS
SS
MMSS
Bluetooth Services (Profiles)Bluetooth Services (Profiles)Supported in CESupported in CEGAPGAP
SPPSPP
DUNDUN
LAPLAP
GOEPGOEP
OPPOPP
FTPFTP
HSHS
HFHF
HIDHID
PANPAN
General Access ProfileGeneral Access Profile
Serial Port ProfileSerial Port Profile
Dialup Networking ProfileDialup Networking Profile
LAN Access ProfileLAN Access Profile
General Object Exchange Profile General Object Exchange Profile
Object Push ProfileObject Push Profile
File Transfer ProfileFile Transfer Profile
Headset ProfileHeadset Profile
Handsfree ProfileHandsfree Profile
Human Input Device ProfileHuman Input Device Profile
Personal Area Network ProfilePersonal Area Network Profile
Bluetooth Enabling Legacy Bluetooth Enabling Legacy Applications: Registering COM portsApplications: Registering COM portsPORTEMUPortParams pp;memset( &pp, 0, sizeof( pp ) );
// connect to serial port profile on device identified by// remoteDeviceAddrpp.device = remoteDeviceAddr;pp.uuidService = SerialPortServiceClass_UUID;pp.uiportflags =
RFCOMM_PORT_FLAGS_REMOTE_DCB;HANDLE h = RegisterDevice (L"COM", index, L"btd.dll",
(DWORD)&pp);
Bluetooth Enabling Legacy Bluetooth Enabling Legacy Applications: Serial Data TransferApplications: Serial Data TransferWCHAR szComPort[30];
// open previously registered COM port for reading and writingwsprintf( szComPort, L"COM%d:", index );
HANDLE hCommPort = CreateFile( szComPort,GENERIC_READ |
GENERIC_WRITE,0, NULL, OPEN_EXISTING, 0,
NULL );
WriteFile( hCommPort, …);ReadFile( hCommPort, …);
// cleanupCloseHandle( hCommPort );DeregisterDevice( h );
BluetoothBluetooth Creating a socketCreating a socket
SOCKET s = socket (AF_BT, SOCKET s = socket (AF_BT, SOCK_STREAM, SOCK_STREAM, BTHPROTO_RFCOMM);BTHPROTO_RFCOMM);
BluetoothBluetooth Connecting a socketConnecting a socket
SOCKADDR_BTH sa;SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BT;sa.addressFamily = AF_BT;
sa.btAddr = b;sa.btAddr = b;
sa.port = channel;sa.port = channel;
connect (s, (SOCKADDR*)&sa, sizeof(sa));connect (s, (SOCKADDR*)&sa, sizeof(sa));
BluetoothBluetooth Listening on a socketListening on a socketSOCKADDR_BTH sa;SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BT;sa.addressFamily = AF_BT;
sa.port = BT_PORT_ANY;sa.port = BT_PORT_ANY;
bind (server, (SOCKADDR *)&sa, sizeof(sa);bind (server, (SOCKADDR *)&sa, sizeof(sa);
getsockname(server, (SOCKADDR *)&sa, &namelen);getsockname(server, (SOCKADDR *)&sa, &namelen);
listen (server, 5);listen (server, 5);
SOCKET s2 = accept (server, (SOCKADDR *)&sa2, SOCKET s2 = accept (server, (SOCKADDR *)&sa2, &size);&size);
BluetoothBluetooth getsocknamegetsocknameUse getsockname to retrieve server channel Use getsockname to retrieve server channel
allocated to socket by a call to bind and allocated to socket by a call to bind and Bluetooth address of local device.Bluetooth address of local device.
SOCKADDR_BTH sab;SOCKADDR_BTH sab;int len = sizeof(sab);int len = sizeof(sab);if (0 == getsockname (s, &sab, &len)) {if (0 == getsockname (s, &sab, &len)) {
wprintf (L”Local Bluetooth device is wprintf (L”Local Bluetooth device is %04x%08x, server channel = %d\n”,%04x%08x, server channel = %d\n”,
GET_NAP(sab.btAddr), GET_NAP(sab.btAddr), GET_SAP(sab.btAddr), sab.port);GET_SAP(sab.btAddr), sab.port);}}
BluetoothBluetooth getpeernamegetpeernameUse getpeername on connected socket to Use getpeername on connected socket to
retrieve Bluetooth address of peer Bluetooth retrieve Bluetooth address of peer Bluetooth device.device.
SOCKADDR_BTH sab;SOCKADDR_BTH sab;int len = sizeof(sab);int len = sizeof(sab);if (0 == getpeername (s, &sab, &len)) {if (0 == getpeername (s, &sab, &len)) {
wprintf (L”Remote Bluetooth device is wprintf (L”Remote Bluetooth device is %04x%08x, connected to %d\n”,%04x%08x, connected to %d\n”,
GET_NAP(sab.btAddr), GET_NAP(sab.btAddr), GET_SAP(sab.btAddr), sab.port);GET_SAP(sab.btAddr), sab.port);}}
BluetoothBluetooth getsockoptgetsockopt
Queries various parameters associated Queries various parameters associated with server channel or connection. The with server channel or connection. The parameters are as follows:parameters are as follows:
s must be Bluetooth sockets must be Bluetooth socket
level must be SOL_RFCOMMlevel must be SOL_RFCOMM
SO_BTH_GET_MTU_MAX,…SO_BTH_GET_MTU_MAX,…
BluetoothBluetooth setsockoptsetsockopt
Configures various parameters Configures various parameters associated with server channel or associated with server channel or connection. The parameters are as connection. The parameters are as follows:follows:
s must be Bluetooth sockets must be Bluetooth socket
level must be SOL_RFCOMMlevel must be SOL_RFCOMM
SO_BTH_AUTHENTICATE, SO_BTH_AUTHENTICATE, SO_BTH_ENCRYPT, …SO_BTH_ENCRYPT, …
BluetoothBluetooth Discovering DevicesDiscovering Devices
WSAQUERYSETWSAQUERYSET wsaq;wsaq;
wsaq.dwNameSpace = NS_BTH;wsaq.dwNameSpace = NS_BTH;
WSALookupServiceBegin (&wsaq, WSALookupServiceBegin (&wsaq, LUP_CONTAINERS, &hLookup);LUP_CONTAINERS, &hLookup);
WSALookupServiceNext (hLookup, WSALookupServiceNext (hLookup, LUP_RETURN_ADDR, &dwSize, LUP_RETURN_ADDR, &dwSize, pwsaResults);pwsaResults);
pNew->b = ((SOCKADDR_BTH *)pwsaResults-pNew->b = ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr>btAddr
BluetoothBluetooth Querying for namesQuerying for names
Change WSALookupServiceNext to Change WSALookupServiceNext to
WSALookupServiceNext (hLookup, WSALookupServiceNext (hLookup, LUP_RETURN_NAME | LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, LUP_RETURN_ADDR, &dwSize, pwsaResults)pwsaResults)
……
wcscpy (pRes->szName, pwsaResults-wcscpy (pRes->szName, pwsaResults->lpszServiceInstanceName);>lpszServiceInstanceName);