Building Bluetooth Applications On The Windows CE 5.0 And Windows Mobile Platforms Gaurav Khanna gkhanna@microsoft.com Developer Evangelist Microsoft.
Post on 01-Apr-2015
226 Views
Preview:
Transcript
Building Bluetooth Building Bluetooth Applications On The Applications On The Windows CE 5.0 And Windows CE 5.0 And Windows Mobile PlatformsWindows Mobile Platforms
Gaurav KhannaGaurav Khannagkhanna@microsoft.comgkhanna@microsoft.comDeveloper EvangelistDeveloper EvangelistMicrosoft IndiaMicrosoft India
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 from Client device listens to broadcasts from discoverable devicesdiscoverable 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
BluetoothBluetooth Creating a socketCreating a socket
SOCKET s = socket (AF_BT, SOCKET s = socket (AF_BT, SOCK_STREAM, SOCK_STREAM, BTHPROTO_RFCOMM);BTHPROTO_RFCOMM);
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()
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);
Bluetooth Enabling Legacy Bluetooth Enabling Legacy Applications: Registering COM portsApplications: Registering COM ports
PORTEMUPortParams 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 Transfer
WCHAR 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 );
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
Inside the Managed Inside the Managed Bluetooth LibraryBluetooth Library
Enumerating Paired Enumerating Paired DevicesDevices
Windows Mobile Managed Windows Mobile Managed Library DownloadLibrary Download
http://msdn.microsoft.com/http://msdn.microsoft.com/embedded/usewinemb/ce/embedded/usewinemb/ce/sharedsrccode/west/sharedsrccode/west/default.aspxdefault.aspx
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
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
Your FeedbackYour Feedbackis Important!is Important!
Please Fill Out the Please Fill Out the feedback formfeedback form
Questions? Questions? gkhanna@microsoft.comgkhanna@microsoft.com
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
top related