SlideShare une entreprise Scribd logo
1  sur  51
Oliver Scheer
Senior Technical Evangelist
Microsoft Deutschland
http://the-oliver.com
Near Field Communications
and Bluetooth
This App   This App
Agenda
3/19/2014Microsoft confidential2
Local Communication with Windows
Phone
Bluetooth Overview
Using Bluetooth from an application
Near Field Communications (NFC)
Using NFC from an application
Local Communication
How to create applications and games that pass information
directly between two devices which are in close proximity
• Local Communication is new to Windows Phone 8
• In Windows Phone 7 processes had to communicate using network connections
• This was difficult because programs had to determine the required IP address
• In Windows Phone 8 there are two new local communication methods available
• Bluetooth
• Can be used for phone to phone and phone to device communication over a range
of up to 10 meters
• Near Field Communication (NFC)
• Can be used for phone to device communication in very close proximity
Local Communication with Windows Phone 8
3/19/2014Microsoft confidential3
Bluetooth
3/19/2014Microsoft confidential4
• Bluetooth is a short range wireless communication technology
• Nominally the range is up to 10 metres, but this can be reduced by the conditions
• Bluetooth provides a means by which one device can provide services for another
• A Bluetooth connection is always between two parties
• A device which has made itself “discoverable” can publish a list of services it provides
• Other devices can search for discoverable devices and then request a the list of resources
that the device provides
• The Bluetooth connection is provided to the program in the form of a StreamSocket
instance linked to the remote device
Bluetooth Communications
3/19/2014Microsoft confidential5
• For one device to be able to communicate with the other the two may need to be paired
• A device must be made “discoverable” before pairing can take place
• Pairing is normally performed via the settings screen on the device
• During the pairing the connection is authenticated
• The user may need to enter a key to validate the connection
• This may be a fixed key, as in the case of devices such as headsets, or generated by
one device and entered on the other
• In some situations applications can communicate without needing to be paired
Bluetooth Pairing
3/19/2014Microsoft confidential6
• There are two Bluetooth communication scenarios supported by Windows Phone
• App to device
• A program running on a Windows Phone can establish a connection to an external
device
• The Windows Phone must be paired with the device
• App to app
• A program running on a Windows Phone can find another application that is offering
a service that the device wishes to use
• In this situation pairing is not required
Bluetooth Scenarios
3/19/2014Microsoft confidential7
• An application running on a Windows Phone 8 device can obtain an enumeration of all the
Bluetooth devices that have been paired with the phone
• The application can then attempt to make a connection to the required service on that
device
• For this to work the Bluetooth service on the phone must be turned on
• The ID_CAP_PROXIMITY and ID_CAP_NETWORKING capabilities must be enabled for the
application to make use of the Bluetooth communications to a device
App to Device
3/19/2014Microsoft confidential8
• The PeerFinder class can be used to search for paired devices
• The search will fail with the exception shown above if Bluetooth is switched off
Finding Paired devices
3/19/20149
try
{
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var peers = await PeerFinder.FindAllPeersAsync();
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
MessageBox.Show("Bluetooth is switched off");
}
• If the user needs to turn Bluetooth on the application can open the appropriate Settings
page using the ConnectionSettingsTask launcher
• Alternatively, use the LaunchUriAsync method:
Enabling Bluetooth
3/19/201410
ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();
Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth"));
• A call of FindAllPeersAsync will return with a list of PeerInformation values, each of
which describes a paired device that was discovered
• This includes a display name for the host, the name of the service it provides and a
HostName value which gives more detail about the device
• If no peers are found the list is empty , with a count of 0
Using the PeerInformation returned from PeerFinder
3/19/201411
StringBuilder list = new StringBuilder();
foreach (PeerInformation p in peers)
{
list.AppendLine(p.DisplayName);
}
• The ConnectAsync method will set up a StreamSocket that connects to a particular
service on the device
• The application must search for the service that it wishes to interact with
• The example below just connects to the service provided by the first peer found
• The method will throw an exception if either parameter is null or empty
Connection to a remote device
3/19/201412
// Just use the first Peer
PeerInformation partner = peers[0];
// Attempt a connection
StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(partner.HostName, partner.ServiceName);
• The Bluetooth discovery and connection methods provide the raw ability to transfer data
between the devices
• This is the StreamSocket that is created as part of the setup process
• The application will have to implement the communications protocol that is required for a
particular device
• Messages in this format will need to be exchanged between the application and the
device
Interacting with Remote Devices via Bluetooth
3/19/2014Microsoft confidential13
• App to App communication allows two programs to interact using Bluetooth to exchange
messages
• An application can wait for and respond to messages from another application
• The PeerFinder class exposes an event which is raised when a communication request is
received from another system
• The communication is still performed using a SocketStream that links the two programs
• The devices do not need to be paired in order to implement app to app connection
• The ID_CAP_PROXIMITY capability must be enabled for the application
App to App communication
3/19/2014Microsoft confidential14
• An application can advertise itself as accepting connections by setting the display name
for the PeerFinder and then starting to advertise the service
• Note that doing this for a long time may have an adverse effect on battery life
Advertising a Service for other Applications
3/19/201415
// Register for incoming connection requests
PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;
// Start advertising ourselves so that our peers can find us
PeerFinder.DisplayName = "PSR";
PeerFinder.Start();
• An application can subscribe to the ConnectionRequested event
• When the event fires the application can then decide whether to accept the request
• It could display a confirmation dialog to the user
Waiting for an Incoming Connection
3/19/201416
// Register for incoming connection requests
PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;
// Start advertising ourselves so that our peers can find us
PeerFinder.DisplayName = "PSR";
PeerFinder.Start();
• The above method creates a connection to an incoming request from “RobsPhone”
• It uses the PeerInformation property of the ConnectionRequestedEventArgs to
determine who is attempting to connect
Responding to a Connection Request
3/19/201417
StreamSocket socket;
async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
{
if ( args.PeerInformation.DisplayName == "RobsPhone" )
{
socket = await PeerFinder.ConnectAsync(args.PeerInformation);
PeerFinder.Stop();
}
}
• This checks the name of the incoming request and only responds to messages from
“RobsPhone”
• The application could instead display a confirmation dialog for the user that identifies the
source of the request
Responding to a Connection Request
3/19/201418
StreamSocket socket;
async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
{
if ( args.PeerInformation.DisplayName == "RobsPhone" )
{
socket = await PeerFinder.ConnectAsync(args.PeerInformation);
PeerFinder.Stop();
}
}
• This statement creates the socket
• In a complete application there should be a handler for any exceptions that this action
might produce
Responding to a Connection Request
3/19/201419
StreamSocket socket;
async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
{
if ( args.PeerInformation.DisplayName == "RobsPhone" )
{
socket = await PeerFinder.ConnectAsync(args.PeerInformation);
PeerFinder.Stop();
}
}
• This statement stops the phone from advertising the connection to other devices
• This will prevent further requests and also improve power consumption
Responding to a Connection Request
3/19/201420
StreamSocket socket;
async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
{
if ( args.PeerInformation.DisplayName == "RobsPhone" )
{
socket = await PeerFinder.ConnectAsync(args.PeerInformation);
PeerFinder.Stop();
}
}
• This method will read a string of text from the stream socket
• The message is read as a length value, followed by that number of characters
Application to Application Communication
3/19/201421
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This is the DataReader that will be used to extract information from the StreamSocket
Application to Application Communication
3/19/201422
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This is the DataReader that will be used to extract information from the StreamSocket
• The DataReader is created the first time the method is called
Application to Application Communication
3/19/201423
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This statement loads 4 bytes from the input stream
Application to Application Communication
3/19/201424
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This statement loads 4 bytes from the input stream
• The incoming 4 bytes are converted into an integer, which is the number of bytes that are
being transferred
Application to Application Communication
3/19/201425
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This statement loads the text of the string
• It uses the value that was supplied as the length
Application to Application Communication
3/19/201426
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This statement loads the text of the string
• It uses the value that was supplied as the length
• Once the bytes have been received they are converted into a string that is returned by the
task
Application to Application Communication
3/19/201427
private DataReader dataReader;
private async Task<string> GetMessage()
{
if (dataReader == null) dataReader = new DataReader(socket.InputStream);
await dataReader.LoadAsync(4);
uint messageLen = (uint)dataReader.ReadInt32();
await dataReader.LoadAsync(messageLen);
return dataReader.ReadString(messageLen);
}
• This GetMessage method is a Task which can be started using the await keyword as
shown above
• This is using the Win RT task management which is provided as part of the Windows 8
Libraries
• When the task completes the message will be set to the received string
Initiating the Read
3/19/201428
string message = await GetMessage();
• The SendMessage method is given a string that it sends to output stream
• It uses a DataWriter to format the output
Writing the message
3/19/201429
DataWriter dataWriter;
private async void SendMessage(string message)
{
if ( dataWriter == null)
dataWriter = new DataWriter(socket.OutputStream);
dataWriter.WriteInt32(message.Length);
await dataWriter.StoreAsync();
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
}
• The dataWriter is created from the socket if it does not already exist
Writing the message
3/19/201430
DataWriter dataWriter;
private async void SendMessage(string message)
{
if ( dataWriter == null)
dataWriter = new DataWriter(socket.OutputStream);
dataWriter.WriteInt32(message.Length);
await dataWriter.StoreAsync();
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
}
• The first item that is written is the length of the string
Writing the message
3/19/201431
DataWriter dataWriter;
private async void SendMessage(string message)
{
if ( dataWriter == null)
dataWriter = new DataWriter(socket.OutputStream);
dataWriter.WriteInt32(message.Length);
await dataWriter.StoreAsync();
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
}
• The first item that is written is the length of the string
• This is followed by the string data itself
Writing the message
3/19/201432
DataWriter dataWriter;
private async void SendMessage(string message)
{
if ( dataWriter == null)
dataWriter = new DataWriter(socket.OutputStream);
dataWriter.WriteInt32(message.Length);
await dataWriter.StoreAsync();
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
}
• The message transmitter method is not implemented as a task
• It can just be called when the message is to be sent
Writing the message
3/19/201433
DataWriter dataWriter;
private async void SendMessage(string message)
{
if ( dataWriter == null)
dataWriter = new DataWriter(socket.OutputStream);
dataWriter.WriteInt32(message.Length);
await dataWriter.StoreAsync();
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
}
• The SendMessage and GetMessage methods implement each end of a simple protocol
that serialises a message between the sender and the receiver
• If you want to send more complex data you can make use of appropriate serialisation
techniques to assemble the message text, just as you would between any processes which
are each end of a data channel
Messages and Protocols
3/19/2014Microsoft confidential34
• It is not possible to use the emulator to debug a program that uses Bluetooth
• An application can check to determine if the emulator is being used and behave
appropriately
Creating Bluetooth Solutions
3/19/2014Microsoft confidential35
if (Microsoft.Devices.Environment.DeviceType == Microsoft.Devices.DeviceType.Emulator)
{
MessageBox.Show("No Bluetooth on the emulator");
}
Near Field
Communications
(NFC)
3/19/2014Microsoft confidential36
• Near Field Communications provide a connection between devices that are very close
together (within 3-4 centimetres)
• The data is transferred at a rate of up to 424 Kbits/second
• It is assumed that this data transfer is intentional so there is not normally any
authentication as such
• The user has positioned their device close to the other device
• The phone can connect to an unpowered NFC chip/tag
Near Field Communications
3/19/2014Microsoft confidential37
• NFC is best for sending small amounts of data between devices and can be used in a
number of different scenarios:
• Connect devices.
• pass configuration from one device to another
• Acquire content
• read “smart” posters that contain digital content in an embedded NFC tag.
• Exchange digital objects
• exchange an electronic business card, or vCard.
Using Near Field Communications
3/19/2014Microsoft confidential38
• There are two ways that an application can use NFC
• Simple transfer of a message from one device to another
• An application can subscribe to message events and receive a string message of a
particular type
• An NFC connection can be used to configure a connection which is implemented using
Bluetooth or WiFi
• This extends the PeerFinder to allow an application to use NFC to quickly set up a
StreamSocket between two devices
Using NFC in applications
3/19/2014Microsoft confidential39
• It is very easy to publish a message to NFC
• Messages have a messagetype and a payload
• The PublishMessage method returns an ID value that uniquely identifies the message that
was sent
• This can then be used to manage the message
Publishing a Message
3/19/2014Microsoft confidential40
ProximityDevice device = ProximityDevice.GetDefault();
// Make sure NFC is supported
if (device!= null)
{
long id = device.PublishMessage("Windows.SampleMessageType", "Hello From Rob!");
}
• The SubscribeForMessage method is given the message type and a delegate
• In the above code the message type is “Windows.SampleMessageType”
• You can add your own message types for your particular solution
Subscribing to Messages
3/19/2014Microsoft confidential41
ProximityDevice device = ProximityDevice.GetDefault();
// Make sure NFC is supported
if (device!= null)
{
long id = device.SubscribeForMessage ("Windows.SampleMessageType", messageReceived);
}
• When a message is received the event is raised and the program can make use of the
received data
• This event is fired when the received message has the same type
• In the case of our program it will fire when a message of type
“Windows.SampleMessageType” is recevied
Receiving Messages
3/19/2014Microsoft confidential42
private void messageReceived(ProximityDevice sender, ProximityMessage message)
{
MessageBox.Show("Message received " + message.DataAsString + " from " + sender.DeviceId);
}
• If an application no longer wishes to subscribe to messages it can use the
StopSubscribingForMessage method to request this
• The method is provided with the message id that was returned when the subscription was
first set up
• An application may need to store this value in in case it is made dormant or tombstoned
when using Near Field Communications
Ending a subscription
3/19/2014Microsoft confidential43
device.StopSubscribingForMessage(id);
• The PeerFinder class allows an application to bind to an event fired when another
application attempts to set up connection with this device
Setting up a StreamSocket using NFC
3/19/2014Microsoft confidential44
ProximityDevice device = ProximityDevice.GetDefault();
// Make sure NFC is supported
if (device != null)
{
PeerFinder.TriggeredConnectionStateChanged += OnTriggeredConnectionStateChanged;
// Start finding peer apps, while making this app discoverable by peers
PeerFinder.Start();
}
• The event arguments contain a state change message
Setting up a StreamSocket using NFC
3/19/2014Microsoft confidential45
void OnTriggeredConnectionStateChanged(object sender,
TriggeredConnectionStateChangedEventArgs args) {
switch (args.State) {
case TriggeredConnectState.Listening: // Connecting as host
break;
case TriggeredConnectState.PeerFound: // Proximity gesture is complete – setting up link
break;
case TriggeredConnectState.Connecting: // Connecting as a client
break;
case TriggeredConnectState.Completed: // Connection completed, get the socket
streamSocket = args.Socket;
break;
case TriggeredConnectState.Canceled: // ongoing connection canceled
break;
case TriggeredConnectState.Failed: // Connection was unsuccessful
break;
}
}
• The StreamSocket will be created using WiFi or Bluetooth to transfer the data
• An application can configure the networking technologies by setting these properties
• They are both set to true by default
• Note that for a successful infrastructure network connection both devices must be
connected to the same subnet and be able to directly connect each other
• It is advisable to make sure that Bluetooth is switched on before using this mechanism,
otherwise it might not be possible for the devices to connect in this way
Using the connection
3/19/2014Microsoft confidential46
PeerFinder.AllowBluetooth = true;
PeerFinder.AllowInfrastructure = true;
• An application running on a Windows Phone device can be interrupted at any time
• An incoming phone call, text message or the user pressing the Start button will cause
the application to be made dormant and possibly tombstoned
• When an application is made dormant all active network connections are disconnected as
it is no longer able to run in response to incoming messages
• However, Windows 8 provides a reconnection feature that an application can use to
quickly re-establish a connection that was disrupted in this way
• An application can persist connection configuration values that allows the socket to be
recreated when it resumes
Recreating a Connection
3/19/2014Microsoft confidential47
• The statements above persist the RawName and RemoteServiceName properties of a socket
into the state storage for an application
• If the application is resumed this information can be used to recreate the network
connection without having to make a new socket
• This information could be stored in isolated storage if you wanted to make the application
re-establish the connection when it is launched
• Need to be mindful of timeouts in this situation
Persisting connection information
3/19/2014Microsoft confidential48
PhoneApplicationService.Current.State["RemoteHostName"] =
socket.Information.RemoteHostName.RawName;
PhoneApplicationService.Current.State["RemoteServiceName"] =
socket.Information.RemoteServiceName;
• When the application restarts it can recreate the connection by using the storage names
• Both of the parties in the socket based connection should use this to allow them to
recover network connections
• However, this option is not present on Windows 8, only on Windows Phone 8
Recreating a Socket
3/19/2014Microsoft confidential49
string storedRemoteHostRawName =
PhoneApplicationService.Current.State["RemoteHostName"] as string;
string storedRemoteServiceName =
PhoneApplicationService.Current.State["RemoteServiceName"] as string;
HostName newRemoteHostName = new HostName(storedRemoteHostRawName);
await socket.ConnectAsync(newRemoteHostName, storedRemoteServiceName);
• Bluetooth and Near Field Communications (NFC) allow two Windows Phones to create
connections to each other and other devices
• To connection a Bluetooth device it must be paired with the phone and support the service
that the application requests
• Two applications can discover each other and exchange messages without pairing
• The connection provided is surfaced as a StreamSocket
• NFC allows a phone to exchange small amounts of data with another phone or device
• Windows Phone 8 provides a means by which an NFC message can be used to instigate a
StreamSocket connection over Bluetooth or WiFi between two devices
• Applications can store socket properties that allow connections to be resumed quickly if
the program is made dormant or tombstoned.
Summary
3/19/2014
The information herein is for informational
purposes only an represents the current view of
Microsoft Corporation as of the date of this
presentation. Because Microsoft must respond
to changing market conditions, it should not be
interpreted to be a commitment on the part of
Microsoft, and Microsoft cannot guarantee the
accuracy of any information provided after the
date of this presentation.
© 2012 Microsoft Corporation.
All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION
IN THIS PRESENTATION.

Contenu connexe

Similaire à Windows Phone 8 - 13 Near Field Communcations and Bluetooth

CNIT 128 8. Android Implementation Issues (Part 3)
CNIT 128 8. Android Implementation Issues (Part 3)CNIT 128 8. Android Implementation Issues (Part 3)
CNIT 128 8. Android Implementation Issues (Part 3)Sam Bowne
 
mumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphonesmumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on SmartphonesAnand Bhojan
 
Bluetooth based-chatting-system-using-android-docx
Bluetooth based-chatting-system-using-android-docxBluetooth based-chatting-system-using-android-docx
Bluetooth based-chatting-system-using-android-docxshanofa sanu
 
Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)
Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)
Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)Giles Greenway
 
Not another *$#@ app: How to avoid IoT fatigue
Not another *$#@ app: How to avoid IoT fatigueNot another *$#@ app: How to avoid IoT fatigue
Not another *$#@ app: How to avoid IoT fatigueRamin Firoozye
 
208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf
208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf
208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdfsmilichitti
 
Communication in android
Communication in androidCommunication in android
Communication in androideleksdev
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
WP7 HUB_Marketplace
WP7 HUB_MarketplaceWP7 HUB_Marketplace
WP7 HUB_MarketplaceMICTT Palma
 
Android Connecting to Internet
Android Connecting to InternetAndroid Connecting to Internet
Android Connecting to InternetParamvir Singh
 
Bluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduinoBluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduinosumit chakraborty
 
Locovore
LocovoreLocovore
Locovoreklee4vp
 
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideSpring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideInexture Solutions
 
Android Penetration Testing - Day 3
Android Penetration Testing - Day 3Android Penetration Testing - Day 3
Android Penetration Testing - Day 3Mohammed Adam
 
Digiplant colloquim
Digiplant colloquimDigiplant colloquim
Digiplant colloquimTyler Belle
 
Mobile App testing guidelines at genora
Mobile App testing guidelines at genoraMobile App testing guidelines at genora
Mobile App testing guidelines at genoraGenora Infotech
 
Android accessories session 2
Android accessories session 2Android accessories session 2
Android accessories session 2Sathish Raju
 
INFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDI
INFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDIINFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDI
INFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDIAman Dwivedi
 
WP7 & Azure
WP7 & AzureWP7 & Azure
WP7 & AzureSam Basu
 

Similaire à Windows Phone 8 - 13 Near Field Communcations and Bluetooth (20)

Firefox OS Presentation
Firefox OS PresentationFirefox OS Presentation
Firefox OS Presentation
 
CNIT 128 8. Android Implementation Issues (Part 3)
CNIT 128 8. Android Implementation Issues (Part 3)CNIT 128 8. Android Implementation Issues (Part 3)
CNIT 128 8. Android Implementation Issues (Part 3)
 
mumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphonesmumble: Framework for Seamless Message Transfer on Smartphones
mumble: Framework for Seamless Message Transfer on Smartphones
 
Bluetooth based-chatting-system-using-android-docx
Bluetooth based-chatting-system-using-android-docxBluetooth based-chatting-system-using-android-docx
Bluetooth based-chatting-system-using-android-docx
 
Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)
Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)
Our Data, Ourselves: The Data Democracy Deficit (EMF CAmp 2014)
 
Not another *$#@ app: How to avoid IoT fatigue
Not another *$#@ app: How to avoid IoT fatigueNot another *$#@ app: How to avoid IoT fatigue
Not another *$#@ app: How to avoid IoT fatigue
 
208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf
208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf
208 jpa016 --multy-user-mobile-bluetooth-two-way-text-chat-pdf
 
Communication in android
Communication in androidCommunication in android
Communication in android
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
WP7 HUB_Marketplace
WP7 HUB_MarketplaceWP7 HUB_Marketplace
WP7 HUB_Marketplace
 
Android Connecting to Internet
Android Connecting to InternetAndroid Connecting to Internet
Android Connecting to Internet
 
Bluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduinoBluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduino
 
Locovore
LocovoreLocovore
Locovore
 
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive GuideSpring Boot for WebRTC Signaling Servers: A Comprehensive Guide
Spring Boot for WebRTC Signaling Servers: A Comprehensive Guide
 
Android Penetration Testing - Day 3
Android Penetration Testing - Day 3Android Penetration Testing - Day 3
Android Penetration Testing - Day 3
 
Digiplant colloquim
Digiplant colloquimDigiplant colloquim
Digiplant colloquim
 
Mobile App testing guidelines at genora
Mobile App testing guidelines at genoraMobile App testing guidelines at genora
Mobile App testing guidelines at genora
 
Android accessories session 2
Android accessories session 2Android accessories session 2
Android accessories session 2
 
INFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDI
INFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDIINFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDI
INFORMATION TECHNOLOGY FOR MANAGERS PRESENTATION BY AMAN DWIVEDI
 
WP7 & Azure
WP7 & AzureWP7 & Azure
WP7 & Azure
 

Plus de Oliver Scheer

Windows Phone 8 - 12 Network Communication
Windows Phone 8 - 12 Network CommunicationWindows Phone 8 - 12 Network Communication
Windows Phone 8 - 12 Network CommunicationOliver Scheer
 
Windows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationWindows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationOliver Scheer
 
Windows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesWindows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesOliver Scheer
 
Windows Phone 8 - 9 Push Notifications
Windows Phone 8 - 9 Push NotificationsWindows Phone 8 - 9 Push Notifications
Windows Phone 8 - 9 Push NotificationsOliver Scheer
 
Windows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local DatabaseWindows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local DatabaseOliver Scheer
 
Windows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsWindows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsOliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentWindows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentOliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 

Plus de Oliver Scheer (10)

Windows Phone 8 - 12 Network Communication
Windows Phone 8 - 12 Network CommunicationWindows Phone 8 - 12 Network Communication
Windows Phone 8 - 12 Network Communication
 
Windows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationWindows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App Communication
 
Windows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesWindows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone Resources
 
Windows Phone 8 - 9 Push Notifications
Windows Phone 8 - 9 Push NotificationsWindows Phone 8 - 9 Push Notifications
Windows Phone 8 - 9 Push Notifications
 
Windows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local DatabaseWindows Phone 8 - 7 Local Database
Windows Phone 8 - 7 Local Database
 
Windows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsWindows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background Agents
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentWindows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 

Dernier

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Dernier (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Windows Phone 8 - 13 Near Field Communcations and Bluetooth

  • 1. Oliver Scheer Senior Technical Evangelist Microsoft Deutschland http://the-oliver.com Near Field Communications and Bluetooth This App   This App
  • 2. Agenda 3/19/2014Microsoft confidential2 Local Communication with Windows Phone Bluetooth Overview Using Bluetooth from an application Near Field Communications (NFC) Using NFC from an application Local Communication How to create applications and games that pass information directly between two devices which are in close proximity
  • 3. • Local Communication is new to Windows Phone 8 • In Windows Phone 7 processes had to communicate using network connections • This was difficult because programs had to determine the required IP address • In Windows Phone 8 there are two new local communication methods available • Bluetooth • Can be used for phone to phone and phone to device communication over a range of up to 10 meters • Near Field Communication (NFC) • Can be used for phone to device communication in very close proximity Local Communication with Windows Phone 8 3/19/2014Microsoft confidential3
  • 5. • Bluetooth is a short range wireless communication technology • Nominally the range is up to 10 metres, but this can be reduced by the conditions • Bluetooth provides a means by which one device can provide services for another • A Bluetooth connection is always between two parties • A device which has made itself “discoverable” can publish a list of services it provides • Other devices can search for discoverable devices and then request a the list of resources that the device provides • The Bluetooth connection is provided to the program in the form of a StreamSocket instance linked to the remote device Bluetooth Communications 3/19/2014Microsoft confidential5
  • 6. • For one device to be able to communicate with the other the two may need to be paired • A device must be made “discoverable” before pairing can take place • Pairing is normally performed via the settings screen on the device • During the pairing the connection is authenticated • The user may need to enter a key to validate the connection • This may be a fixed key, as in the case of devices such as headsets, or generated by one device and entered on the other • In some situations applications can communicate without needing to be paired Bluetooth Pairing 3/19/2014Microsoft confidential6
  • 7. • There are two Bluetooth communication scenarios supported by Windows Phone • App to device • A program running on a Windows Phone can establish a connection to an external device • The Windows Phone must be paired with the device • App to app • A program running on a Windows Phone can find another application that is offering a service that the device wishes to use • In this situation pairing is not required Bluetooth Scenarios 3/19/2014Microsoft confidential7
  • 8. • An application running on a Windows Phone 8 device can obtain an enumeration of all the Bluetooth devices that have been paired with the phone • The application can then attempt to make a connection to the required service on that device • For this to work the Bluetooth service on the phone must be turned on • The ID_CAP_PROXIMITY and ID_CAP_NETWORKING capabilities must be enabled for the application to make use of the Bluetooth communications to a device App to Device 3/19/2014Microsoft confidential8
  • 9. • The PeerFinder class can be used to search for paired devices • The search will fail with the exception shown above if Bluetooth is switched off Finding Paired devices 3/19/20149 try { PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; var peers = await PeerFinder.FindAllPeersAsync(); } catch (Exception ex) { if ((uint)ex.HResult == 0x8007048F) MessageBox.Show("Bluetooth is switched off"); }
  • 10. • If the user needs to turn Bluetooth on the application can open the appropriate Settings page using the ConnectionSettingsTask launcher • Alternatively, use the LaunchUriAsync method: Enabling Bluetooth 3/19/201410 ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask(); connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth; connectionSettingsTask.Show(); Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth"));
  • 11. • A call of FindAllPeersAsync will return with a list of PeerInformation values, each of which describes a paired device that was discovered • This includes a display name for the host, the name of the service it provides and a HostName value which gives more detail about the device • If no peers are found the list is empty , with a count of 0 Using the PeerInformation returned from PeerFinder 3/19/201411 StringBuilder list = new StringBuilder(); foreach (PeerInformation p in peers) { list.AppendLine(p.DisplayName); }
  • 12. • The ConnectAsync method will set up a StreamSocket that connects to a particular service on the device • The application must search for the service that it wishes to interact with • The example below just connects to the service provided by the first peer found • The method will throw an exception if either parameter is null or empty Connection to a remote device 3/19/201412 // Just use the first Peer PeerInformation partner = peers[0]; // Attempt a connection StreamSocket socket = new StreamSocket(); await socket.ConnectAsync(partner.HostName, partner.ServiceName);
  • 13. • The Bluetooth discovery and connection methods provide the raw ability to transfer data between the devices • This is the StreamSocket that is created as part of the setup process • The application will have to implement the communications protocol that is required for a particular device • Messages in this format will need to be exchanged between the application and the device Interacting with Remote Devices via Bluetooth 3/19/2014Microsoft confidential13
  • 14. • App to App communication allows two programs to interact using Bluetooth to exchange messages • An application can wait for and respond to messages from another application • The PeerFinder class exposes an event which is raised when a communication request is received from another system • The communication is still performed using a SocketStream that links the two programs • The devices do not need to be paired in order to implement app to app connection • The ID_CAP_PROXIMITY capability must be enabled for the application App to App communication 3/19/2014Microsoft confidential14
  • 15. • An application can advertise itself as accepting connections by setting the display name for the PeerFinder and then starting to advertise the service • Note that doing this for a long time may have an adverse effect on battery life Advertising a Service for other Applications 3/19/201415 // Register for incoming connection requests PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested; // Start advertising ourselves so that our peers can find us PeerFinder.DisplayName = "PSR"; PeerFinder.Start();
  • 16. • An application can subscribe to the ConnectionRequested event • When the event fires the application can then decide whether to accept the request • It could display a confirmation dialog to the user Waiting for an Incoming Connection 3/19/201416 // Register for incoming connection requests PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested; // Start advertising ourselves so that our peers can find us PeerFinder.DisplayName = "PSR"; PeerFinder.Start();
  • 17. • The above method creates a connection to an incoming request from “RobsPhone” • It uses the PeerInformation property of the ConnectionRequestedEventArgs to determine who is attempting to connect Responding to a Connection Request 3/19/201417 StreamSocket socket; async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args) { if ( args.PeerInformation.DisplayName == "RobsPhone" ) { socket = await PeerFinder.ConnectAsync(args.PeerInformation); PeerFinder.Stop(); } }
  • 18. • This checks the name of the incoming request and only responds to messages from “RobsPhone” • The application could instead display a confirmation dialog for the user that identifies the source of the request Responding to a Connection Request 3/19/201418 StreamSocket socket; async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args) { if ( args.PeerInformation.DisplayName == "RobsPhone" ) { socket = await PeerFinder.ConnectAsync(args.PeerInformation); PeerFinder.Stop(); } }
  • 19. • This statement creates the socket • In a complete application there should be a handler for any exceptions that this action might produce Responding to a Connection Request 3/19/201419 StreamSocket socket; async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args) { if ( args.PeerInformation.DisplayName == "RobsPhone" ) { socket = await PeerFinder.ConnectAsync(args.PeerInformation); PeerFinder.Stop(); } }
  • 20. • This statement stops the phone from advertising the connection to other devices • This will prevent further requests and also improve power consumption Responding to a Connection Request 3/19/201420 StreamSocket socket; async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args) { if ( args.PeerInformation.DisplayName == "RobsPhone" ) { socket = await PeerFinder.ConnectAsync(args.PeerInformation); PeerFinder.Stop(); } }
  • 21. • This method will read a string of text from the stream socket • The message is read as a length value, followed by that number of characters Application to Application Communication 3/19/201421 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 22. • This is the DataReader that will be used to extract information from the StreamSocket Application to Application Communication 3/19/201422 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 23. • This is the DataReader that will be used to extract information from the StreamSocket • The DataReader is created the first time the method is called Application to Application Communication 3/19/201423 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 24. • This statement loads 4 bytes from the input stream Application to Application Communication 3/19/201424 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 25. • This statement loads 4 bytes from the input stream • The incoming 4 bytes are converted into an integer, which is the number of bytes that are being transferred Application to Application Communication 3/19/201425 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 26. • This statement loads the text of the string • It uses the value that was supplied as the length Application to Application Communication 3/19/201426 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 27. • This statement loads the text of the string • It uses the value that was supplied as the length • Once the bytes have been received they are converted into a string that is returned by the task Application to Application Communication 3/19/201427 private DataReader dataReader; private async Task<string> GetMessage() { if (dataReader == null) dataReader = new DataReader(socket.InputStream); await dataReader.LoadAsync(4); uint messageLen = (uint)dataReader.ReadInt32(); await dataReader.LoadAsync(messageLen); return dataReader.ReadString(messageLen); }
  • 28. • This GetMessage method is a Task which can be started using the await keyword as shown above • This is using the Win RT task management which is provided as part of the Windows 8 Libraries • When the task completes the message will be set to the received string Initiating the Read 3/19/201428 string message = await GetMessage();
  • 29. • The SendMessage method is given a string that it sends to output stream • It uses a DataWriter to format the output Writing the message 3/19/201429 DataWriter dataWriter; private async void SendMessage(string message) { if ( dataWriter == null) dataWriter = new DataWriter(socket.OutputStream); dataWriter.WriteInt32(message.Length); await dataWriter.StoreAsync(); dataWriter.WriteString(message); await dataWriter.StoreAsync(); }
  • 30. • The dataWriter is created from the socket if it does not already exist Writing the message 3/19/201430 DataWriter dataWriter; private async void SendMessage(string message) { if ( dataWriter == null) dataWriter = new DataWriter(socket.OutputStream); dataWriter.WriteInt32(message.Length); await dataWriter.StoreAsync(); dataWriter.WriteString(message); await dataWriter.StoreAsync(); }
  • 31. • The first item that is written is the length of the string Writing the message 3/19/201431 DataWriter dataWriter; private async void SendMessage(string message) { if ( dataWriter == null) dataWriter = new DataWriter(socket.OutputStream); dataWriter.WriteInt32(message.Length); await dataWriter.StoreAsync(); dataWriter.WriteString(message); await dataWriter.StoreAsync(); }
  • 32. • The first item that is written is the length of the string • This is followed by the string data itself Writing the message 3/19/201432 DataWriter dataWriter; private async void SendMessage(string message) { if ( dataWriter == null) dataWriter = new DataWriter(socket.OutputStream); dataWriter.WriteInt32(message.Length); await dataWriter.StoreAsync(); dataWriter.WriteString(message); await dataWriter.StoreAsync(); }
  • 33. • The message transmitter method is not implemented as a task • It can just be called when the message is to be sent Writing the message 3/19/201433 DataWriter dataWriter; private async void SendMessage(string message) { if ( dataWriter == null) dataWriter = new DataWriter(socket.OutputStream); dataWriter.WriteInt32(message.Length); await dataWriter.StoreAsync(); dataWriter.WriteString(message); await dataWriter.StoreAsync(); }
  • 34. • The SendMessage and GetMessage methods implement each end of a simple protocol that serialises a message between the sender and the receiver • If you want to send more complex data you can make use of appropriate serialisation techniques to assemble the message text, just as you would between any processes which are each end of a data channel Messages and Protocols 3/19/2014Microsoft confidential34
  • 35. • It is not possible to use the emulator to debug a program that uses Bluetooth • An application can check to determine if the emulator is being used and behave appropriately Creating Bluetooth Solutions 3/19/2014Microsoft confidential35 if (Microsoft.Devices.Environment.DeviceType == Microsoft.Devices.DeviceType.Emulator) { MessageBox.Show("No Bluetooth on the emulator"); }
  • 37. • Near Field Communications provide a connection between devices that are very close together (within 3-4 centimetres) • The data is transferred at a rate of up to 424 Kbits/second • It is assumed that this data transfer is intentional so there is not normally any authentication as such • The user has positioned their device close to the other device • The phone can connect to an unpowered NFC chip/tag Near Field Communications 3/19/2014Microsoft confidential37
  • 38. • NFC is best for sending small amounts of data between devices and can be used in a number of different scenarios: • Connect devices. • pass configuration from one device to another • Acquire content • read “smart” posters that contain digital content in an embedded NFC tag. • Exchange digital objects • exchange an electronic business card, or vCard. Using Near Field Communications 3/19/2014Microsoft confidential38
  • 39. • There are two ways that an application can use NFC • Simple transfer of a message from one device to another • An application can subscribe to message events and receive a string message of a particular type • An NFC connection can be used to configure a connection which is implemented using Bluetooth or WiFi • This extends the PeerFinder to allow an application to use NFC to quickly set up a StreamSocket between two devices Using NFC in applications 3/19/2014Microsoft confidential39
  • 40. • It is very easy to publish a message to NFC • Messages have a messagetype and a payload • The PublishMessage method returns an ID value that uniquely identifies the message that was sent • This can then be used to manage the message Publishing a Message 3/19/2014Microsoft confidential40 ProximityDevice device = ProximityDevice.GetDefault(); // Make sure NFC is supported if (device!= null) { long id = device.PublishMessage("Windows.SampleMessageType", "Hello From Rob!"); }
  • 41. • The SubscribeForMessage method is given the message type and a delegate • In the above code the message type is “Windows.SampleMessageType” • You can add your own message types for your particular solution Subscribing to Messages 3/19/2014Microsoft confidential41 ProximityDevice device = ProximityDevice.GetDefault(); // Make sure NFC is supported if (device!= null) { long id = device.SubscribeForMessage ("Windows.SampleMessageType", messageReceived); }
  • 42. • When a message is received the event is raised and the program can make use of the received data • This event is fired when the received message has the same type • In the case of our program it will fire when a message of type “Windows.SampleMessageType” is recevied Receiving Messages 3/19/2014Microsoft confidential42 private void messageReceived(ProximityDevice sender, ProximityMessage message) { MessageBox.Show("Message received " + message.DataAsString + " from " + sender.DeviceId); }
  • 43. • If an application no longer wishes to subscribe to messages it can use the StopSubscribingForMessage method to request this • The method is provided with the message id that was returned when the subscription was first set up • An application may need to store this value in in case it is made dormant or tombstoned when using Near Field Communications Ending a subscription 3/19/2014Microsoft confidential43 device.StopSubscribingForMessage(id);
  • 44. • The PeerFinder class allows an application to bind to an event fired when another application attempts to set up connection with this device Setting up a StreamSocket using NFC 3/19/2014Microsoft confidential44 ProximityDevice device = ProximityDevice.GetDefault(); // Make sure NFC is supported if (device != null) { PeerFinder.TriggeredConnectionStateChanged += OnTriggeredConnectionStateChanged; // Start finding peer apps, while making this app discoverable by peers PeerFinder.Start(); }
  • 45. • The event arguments contain a state change message Setting up a StreamSocket using NFC 3/19/2014Microsoft confidential45 void OnTriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args) { switch (args.State) { case TriggeredConnectState.Listening: // Connecting as host break; case TriggeredConnectState.PeerFound: // Proximity gesture is complete – setting up link break; case TriggeredConnectState.Connecting: // Connecting as a client break; case TriggeredConnectState.Completed: // Connection completed, get the socket streamSocket = args.Socket; break; case TriggeredConnectState.Canceled: // ongoing connection canceled break; case TriggeredConnectState.Failed: // Connection was unsuccessful break; } }
  • 46. • The StreamSocket will be created using WiFi or Bluetooth to transfer the data • An application can configure the networking technologies by setting these properties • They are both set to true by default • Note that for a successful infrastructure network connection both devices must be connected to the same subnet and be able to directly connect each other • It is advisable to make sure that Bluetooth is switched on before using this mechanism, otherwise it might not be possible for the devices to connect in this way Using the connection 3/19/2014Microsoft confidential46 PeerFinder.AllowBluetooth = true; PeerFinder.AllowInfrastructure = true;
  • 47. • An application running on a Windows Phone device can be interrupted at any time • An incoming phone call, text message or the user pressing the Start button will cause the application to be made dormant and possibly tombstoned • When an application is made dormant all active network connections are disconnected as it is no longer able to run in response to incoming messages • However, Windows 8 provides a reconnection feature that an application can use to quickly re-establish a connection that was disrupted in this way • An application can persist connection configuration values that allows the socket to be recreated when it resumes Recreating a Connection 3/19/2014Microsoft confidential47
  • 48. • The statements above persist the RawName and RemoteServiceName properties of a socket into the state storage for an application • If the application is resumed this information can be used to recreate the network connection without having to make a new socket • This information could be stored in isolated storage if you wanted to make the application re-establish the connection when it is launched • Need to be mindful of timeouts in this situation Persisting connection information 3/19/2014Microsoft confidential48 PhoneApplicationService.Current.State["RemoteHostName"] = socket.Information.RemoteHostName.RawName; PhoneApplicationService.Current.State["RemoteServiceName"] = socket.Information.RemoteServiceName;
  • 49. • When the application restarts it can recreate the connection by using the storage names • Both of the parties in the socket based connection should use this to allow them to recover network connections • However, this option is not present on Windows 8, only on Windows Phone 8 Recreating a Socket 3/19/2014Microsoft confidential49 string storedRemoteHostRawName = PhoneApplicationService.Current.State["RemoteHostName"] as string; string storedRemoteServiceName = PhoneApplicationService.Current.State["RemoteServiceName"] as string; HostName newRemoteHostName = new HostName(storedRemoteHostRawName); await socket.ConnectAsync(newRemoteHostName, storedRemoteServiceName);
  • 50. • Bluetooth and Near Field Communications (NFC) allow two Windows Phones to create connections to each other and other devices • To connection a Bluetooth device it must be paired with the phone and support the service that the application requests • Two applications can discover each other and exchange messages without pairing • The connection provided is surfaced as a StreamSocket • NFC allows a phone to exchange small amounts of data with another phone or device • Windows Phone 8 provides a means by which an NFC message can be used to instigate a StreamSocket connection over Bluetooth or WiFi between two devices • Applications can store socket properties that allow connections to be resumed quickly if the program is made dormant or tombstoned. Summary 3/19/2014
  • 51. The information herein is for informational purposes only an represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.