SlideShare ist ein Scribd-Unternehmen logo
1 von 44
A Message from the Team

       We want to hear from you – app developers!

Microsoft will be hosting a live Q&A session via Lync for your company to
ask questions, or provide feedback, on the Windows 8 Proximity/NFC
APIs. You’ll have an opportunity to communicate directly with product
engineers who built the proximity APIs.

  March 12th from 5 – 6 PM local Belgium time (GMT+1)
                  http://aka.ms/gwevca
Near Field Communication (NFC)

Enables devices to communicate wirelessly while in close proximity (3 to
4 cm) of each other
 "Devices" can be powered or passive (e.g., smart tag)
May be used to establish Bluetooth, WiFi, and WiFi Direct connections
for non-proximate transfers
Supported by many platforms, including Windows 8, Windows Phone
8, Android, and Symbian
Standards driven by NFC Forum (160+ members)
NFC Modes and Use Cases

NFC enables a multitude of "tap and do" scenarios which are intuitive to
users and require no setup

     Read and write        Tap devices to establish
  information stored in         peer-to-peer             Tap a payment
    passive NFC tags      communication and share     terminal to execute
      ("smart tags")              content             electronic payments




     Reader/Writer Mode         Peer-to-Peer Mode       Card Emulation Mode
NFC Data Exchange Format (NDEF)

Lightweight, binary, platform-independent format for NFC messages with
variable-length payloads


    Read and write
                                                    Or store them
    them with
                                                    in inductively
    smartphones
                                                    powered
    and other
                                                    smart tags
    mobile devices
NFC in WinRT

                                    Tap For


              NFC                                     Socket
           Connection                               Connection
         ProximityDevice                              PeerFinder
      Exchange NDEF messages and                  Exchange data using
      Windows messages using SNEP            Bluetooth, WiFi, or WiFi Direct*

          * WiFi Direct supported in Windows 8 but not Windows Phone 8
Proximity Capability

Windows apps that use proximity networking must indicate that through
their manifests




   Windows 8                                       Windows Phone 8
The ProximityDevice Class

Provides methods for driving NFC devices
 Publishing NDEF messages to devices and tags
 Subscribing to NDEF messages from devices and tags
 Identifying on-board proximity devices
Contains properties for retrieving transfer rates and other information
about proximity devices
Fires events when other proximity devices arrive and depart
Detecting NFC Support
var device = ProximityDevice.GetDefault();

if (device != null)
{
    // This device supports NFC
}
Getting Device Information
var device = ProximityDevice.GetDefault();

if (device != null)
{
    var id = device.DeviceId;          // Device ID
    var bps = device.BitsPerSecond;    // Max transfer rate (bps)
    var size = device.MaxMessageBytes; // Max message size (bytes)
}
Detecting Arrivals and Departures
var device = ProximityDevice.GetDefault();

if (device != null)
{
    device.DeviceArrived += OnDeviceArrived;
    device.DeviceDeparted += OnDeviceDeparted;
}

void OnDeviceArrived(ProximityDevice sender)
{
    // Proximity device arrived
}

void OnDeviceDeparted(ProximityDevice sender)
{
    // Proximity device departed
}
PublishMessage

ProximityDevice.PublishMessage publishes Windows.subtype messages
to other devices
 Supported by Windows and Windows Phone
    Not supported by other platforms
 subtype can be anything you want
 Supports transmission of string data
 Does not publish to smart tags
ProximityDevice.StopPublishingMessage stops publishing a message
Using PublishMessage
// Publish without a completed callback
device.PublishMessage("Windows.Sample", "Hello, NFC!");

// Publish with a completed callback
device.PublishMessage("Windows.Sample", "Hello, NFC!", OnMessageTransmitted);
  .
  .
  .
void OnMessageTransmitted(ProximityDevice sender, long messageId)
{
    // Stop publishing the message once it's delivered
    device.StopPublishingMessage(messageId);
}
Subscribing to Messages

ProximityDevice.SubscribeForMessage subscribes to NDEF messages
of the specified type
       "Windows.subtype" messages
       "WindowsUri" messages for URIs
       "WriteableTag" messages for writeable tags
       "NDEF[:filter]" messages for other message types
        e.g., NDEF, NDEF:ext, and NDEF:wkt.U
ProximityDevice.StopSubscribingForMessage revokes a message
subscription
Using SubscribeForMessage
device.SubscribeForMessage("Windows.Sample", OnReceived);
  .
  .
  .
void OnReceived(ProximityDevice sender, ProximityMessage message)
{
    string type = message.MessageType; // e.g., "Windows.Sample"
    string data = message.DataAsString; // e.g., "Hello, NFC!"

    // Do this now, or do it later to continue subscribing
    device.StopSubscribingForMessage(message.SubscriptionId);
}
The PeerFinder Class

Provides API for establishing socket connections via NFC for direct app-
to-app communications
 Methods for establishing connections
 Properties for feature detection, connecting to other platforms, and exerting control
  over transport types
 Events signifying connection requests
TriggeredConnectionStateChanged event makes tap-to-connect gestures
simple and easy
Detecting Tap-to-Connect Support
if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) != 0)
{
    // This device supports tap-to-connect
}
Establishing a Socket Connection
if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) != 0)
{
    PeerFinder.TriggeredConnectionStateChanged += OnTriggered;
    PeerFinder.Start();
}

void OnTriggered(object sender,
    TriggeredConnectionStateChangedEventArgs e)
{
    if (e.State == TriggeredConnectState.Completed)
    {
        var socket = e.Socket; // StreamSocket
        PeerFinder.Stop();
    }
}
Triggered Connection State
void OnTriggered(object sender, TriggeredConnectionStateChangedEventArgs e)
{
    switch (e.State)
    {
        case TriggeredConnectState.Listening:
            break;
        case TriggeredConnectState.PeerFound: // OK to move devices apart
            break;
        case TriggeredConnectState.Connecting: // Establishing socket connection
            break;
        case TriggeredConnectState.Completed: // StreamSocket reference in e.Socket
            break;
        case TriggeredConnectState.Canceled: // Connection was closed
            break;
        case TriggeredConnectState.Failed: // Connection could not be established
            break;
    }
}
Controlling the Transport Type
// All values default to true
PeerFinder.AllowBluetooth = true;      // Bluetooth
PeerFinder.AllowInfrastructure = true; // WiFi
PeerFinder.AllowWiFiDirect = true;     // WiFi Direct (Win8 only)
Alternate (App) Identities

PeerFinder.AlternateIdentities enables apps on different platforms to
connect to each other
 e.g., Windows to Windows Phone
In a Windows app, add entry identifying corresponding app on Windows
Phone
 App ID = {App product ID}
In a Windows Phone app, add entry identifying corresponding app on
Windows
 App ID = {Package family name}!App
Enabling Windows Connections
PeerFinder.AlternateIdentities.Add(
    "Windows", // Platform identifier
    "f5bbba4f-c852-4e33-9e5d-54fe1c732524_ky5brtva589yy!App"
);
Enabling Windows Phone Connections
PeerFinder.AlternateIdentities.Add(
    "WindowsPhone", // Platform identifier
    "{b2c65896-3f48-4ea9-8c1c-773a17c38bff}"
);
PublishBinaryMessage

Publishes NDEF messages to devices and tags
 WriteTag messages for writing to smart tags
    Windows:WriteTag, WindowsUri:WriteTag, LaunchApp:WriteTag, and NDEF:WriteTag
    NDEF:WriteTag supports smart posters, Android Application Records (AARs), and more
 NDEF messages for publishing to other devices
 WindowsMime messages to other devices
Use NDEF Library for Proximity APIs for help formatting binary NDEF
messages
Getting an NFC Tag's Capacity
device.SubscribeForMessage("WriteableTag", OnReceived);
  .
  .
  .
void OnReceived(ProximityDevice sender, ProximityMessage message)
{
    var size = BitConverter.ToInt32(message.Data.ToArray(), 0);
}
Writing URIs to NFC Tags
using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE })
{
    writer.WriteString("http://www.wintellect.com");
    var buffer = writer.DetachBuffer();
    device.PublishBinaryMessage("WindowsUri:WriteTag", buffer);
}
Writing Windows Launch Tags
using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE })
{
    string tag =
        "argument" +                                  // Optional launch argument
        "tWindowst" +                               // Platform identifier
        "1ED5AEA5.AngryBirdsSpace_p2gbknwb5d8r2!App"; // App ID

    writer.WriteString(tag);
    var buffer = writer.DetachBuffer();
    device.PublishBinaryMessage("LaunchApp:WriteTag", buffer);
}
Writing Windows Phone Launch Tags
using (var writer = new DataWriter { UnicodeEncoding   = UnicodeEncoding.Utf16LE })
{
    string tag =
        "argument" +                              //   Optional launch argument
        "tWindowsPhonet" +                      //   Platform identifier
        "{afc3dfcf-8429-4e0d-9df8-4038939b5e75}"; //   App ID

    writer.WriteString(tag);
    var buffer = writer.DetachBuffer();
    device.PublishBinaryMessage("LaunchApp:WriteTag", buffer);
}
Writing Dual Launch Tags
using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE })
{
    string tag =
        "argument" +
        "tWindowst" +
        "1ED5AEA5.AngryBirdsSpace_p2gbknwb5d8r2!App" +
        "tWindowsPhonet" +
        "{afc3dfcf-8429-4e0d-9df8-4038939b5e75}";

    writer.WriteString(tag);
    var buffer = writer.DetachBuffer();
    device.PublishBinaryMessage("LaunchApp:WriteTag", buffer);
}
Using Launch Arguments (Windows)
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // If this page was activated from an NFC tag or a
    // secondary tile, retrieve the launch argument
    if (e.Parameter != null && e.Parameter != String.Empty)
    {
        string arg = (string)e.Parameter;
        // TODO: Use the launch argument
    }
}
Using Launch Arguments (Phone)
private const string _key = "ms_nfp_launchargs";
  .
  .
  .
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // If this page was activated from an NFC tag, retrieve the launch argument
    if (NavigationContext.QueryString.ContainsKey(_key))
    {
        string arg = NavigationContext.QueryString[_key];
        // TODO: Use the launch argument
    }
}
NDEF Library for Proximity APIs

Free, open-source library for reading and writing NDEF
messages, including smart posters and AARs
Compatible with Windows 8 and WP8
Writing a Smart Poster Tag
var record = new NdefSpRecord();
record.Uri = "http://www.wintellect.com";
record.NfcAction = NdefSpActRecord.NfcActionType.DoAction;
record.AddTitle(new NdefTextRecord { Text = "Wintellect", LanguageCode = "en" });

var message = new NdefMessage { record };

device.PublishBinaryMessage("NDEF:WriteTag", message.ToByteArray().AsBuffer());
Reading a Smart Poster Tag
device.SubscribeForMessage("NDEF", OnMessageReceived);
  ...
void OnMessageReceived(ProximityDevice sender, ProximityMessage message)
{
    var ndef = NdefMessage.FromByteArray(message.Data.ToArray());

    foreach (NdefRecord record in ndef)
    {
        if (record.CheckSpecializedType(false) == typeof(NdefSpRecord))
        {
            var poster = new NdefSpRecord(record);
            var uri = poster.Uri;
            for (int i = 0; i < poster.TitleCount(); i++)
                var title = poster.Titles[i].Text;
        }
    }
}
Writing an Android Launch Tag
var record = new NdefAndroidAppRecord();
record.PackageName = "com.adobe.reader";

var message = new NdefMessage { record };

device.PublishBinaryMessage("NDEF:WriteTag", message.ToByteArray().AsBuffer());
PublishUriMessage

Publishes URI messages to other devices
 Messages include standard NDEF URI records
 Compatible with Windows and non-Windows devices
 Only one URI message can be published at a time
URI messages launch URIs on target devices
 http:// protocol launches browser and shows the specified URL
  (e.g., http://www.wintellect.com)
 Other protocols launch apps registered for those protocols and can include launch
  parameters
Great way to launch apps on other platforms!
Launching a Browser
var uri = new Uri("http://www.wintellect.com");
device.PublishUriMessage(uri, OnMessageTransmitted);
  .
  .
  .
void OnMessageTransmitted(ProximityDevice sender, long messageId)
{
    // Message delivered
}
Launching Skype
var uri = new Uri("skype:lori.prosise?call");
device.PublishUriMessage(uri, OnMessageTransmitted);
  .
  .
  .
void OnMessageTransmitted(ProximityDevice sender, long messageId)
{
    // Message delivered
}
Subscribing to URI Messages
device.SubscribeForMessage("WindowsUri", OnUriReceived);
      .
      .
      .
private async void OnUriReceived(ProximityDevice sender, ProximityMessage message)
{
    var array = message.Data.ToArray();
    var uri = Encoding.Unicode.GetString(array, 0, array.Length);
}
02 dev room6__tapand_go_jeffprosise_9Tap and Go: Proximity Networking in WinRT

Weitere ähnliche Inhalte

Ähnlich wie 02 dev room6__tapand_go_jeffprosise_9Tap and Go: Proximity Networking in WinRT

NetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. SecurityNetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. Securitywebhostingguy
 
NetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. SecurityNetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. Securitywebhostingguy
 
Manish Chasta - Securing Android Applications
Manish Chasta - Securing Android ApplicationsManish Chasta - Securing Android Applications
Manish Chasta - Securing Android ApplicationsPositive Hack Days
 
NFC - quick primer
NFC - quick primerNFC - quick primer
NFC - quick primeramsanjeev
 
Windows Phone 8 Advanced Developers Conference
Windows Phone 8 Advanced Developers ConferenceWindows Phone 8 Advanced Developers Conference
Windows Phone 8 Advanced Developers ConferenceDamir Dobric
 
Adc2012 windows phone 8
Adc2012 windows phone 8Adc2012 windows phone 8
Adc2012 windows phone 8AlexanderGoetz
 
Windows phone7 By Subodh
Windows phone7 By Subodh Windows phone7 By Subodh
Windows phone7 By Subodh Prashant Singh
 
A Day in the Life of a Metro-veloper
A Day in the Life of a Metro-veloperA Day in the Life of a Metro-veloper
A Day in the Life of a Metro-veloperDucas Francis
 
WebRTC Introduction & Basics
WebRTC Introduction & BasicsWebRTC Introduction & Basics
WebRTC Introduction & BasicsMuhammad Ali
 
MSMDC_CLI363
MSMDC_CLI363MSMDC_CLI363
MSMDC_CLI363mokacao
 
Droidcon2013 key2 share_dmitrienko_fraunhofer
Droidcon2013 key2 share_dmitrienko_fraunhoferDroidcon2013 key2 share_dmitrienko_fraunhofer
Droidcon2013 key2 share_dmitrienko_fraunhoferDroidcon Berlin
 
Windows Phone Application Platform
Windows Phone Application PlatformWindows Phone Application Platform
Windows Phone Application PlatformDave Bost
 
An end-to-end experience of Windows Phone 7 development (Part 2)
An end-to-end experience of Windows Phone 7 development (Part 2)An end-to-end experience of Windows Phone 7 development (Part 2)
An end-to-end experience of Windows Phone 7 development (Part 2)rudigrobler
 

Ähnlich wie 02 dev room6__tapand_go_jeffprosise_9Tap and Go: Proximity Networking in WinRT (20)

NetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. SecurityNetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. Security
 
NetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. SecurityNetOp Tech GmbH Remote Control. Education. Security
NetOp Tech GmbH Remote Control. Education. Security
 
Manish Chasta - Securing Android Applications
Manish Chasta - Securing Android ApplicationsManish Chasta - Securing Android Applications
Manish Chasta - Securing Android Applications
 
Windows 8.1 Sockets
Windows 8.1 SocketsWindows 8.1 Sockets
Windows 8.1 Sockets
 
NFC - quick primer
NFC - quick primerNFC - quick primer
NFC - quick primer
 
Windows Phone 8 Advanced Developers Conference
Windows Phone 8 Advanced Developers ConferenceWindows Phone 8 Advanced Developers Conference
Windows Phone 8 Advanced Developers Conference
 
Adc2012 windows phone 8
Adc2012 windows phone 8Adc2012 windows phone 8
Adc2012 windows phone 8
 
Windows phone7 By Subodh
Windows phone7 By Subodh Windows phone7 By Subodh
Windows phone7 By Subodh
 
Expo java
Expo javaExpo java
Expo java
 
A Day in the Life of a Metro-veloper
A Day in the Life of a Metro-veloperA Day in the Life of a Metro-veloper
A Day in the Life of a Metro-veloper
 
Pc03
Pc03Pc03
Pc03
 
WebRTC Introduction & Basics
WebRTC Introduction & BasicsWebRTC Introduction & Basics
WebRTC Introduction & Basics
 
MSMDC_CLI363
MSMDC_CLI363MSMDC_CLI363
MSMDC_CLI363
 
Droidcon2013 key2 share_dmitrienko_fraunhofer
Droidcon2013 key2 share_dmitrienko_fraunhoferDroidcon2013 key2 share_dmitrienko_fraunhofer
Droidcon2013 key2 share_dmitrienko_fraunhofer
 
P2P .NET short seminar
P2P .NET short seminarP2P .NET short seminar
P2P .NET short seminar
 
Windows Phone Application Platform
Windows Phone Application PlatformWindows Phone Application Platform
Windows Phone Application Platform
 
Under The Hood
Under The HoodUnder The Hood
Under The Hood
 
Windows Mobile
Windows MobileWindows Mobile
Windows Mobile
 
IoT setup and pairing
IoT setup and pairingIoT setup and pairing
IoT setup and pairing
 
An end-to-end experience of Windows Phone 7 development (Part 2)
An end-to-end experience of Windows Phone 7 development (Part 2)An end-to-end experience of Windows Phone 7 development (Part 2)
An end-to-end experience of Windows Phone 7 development (Part 2)
 

Mehr von Microsoft Developer Network (MSDN) - Belgium and Luxembourg

Mehr von Microsoft Developer Network (MSDN) - Belgium and Luxembourg (20)

Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015
 
Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015
 
Executive Summit for ISV & Application builders - Internet of Things
Executive Summit for ISV & Application builders - Internet of ThingsExecutive Summit for ISV & Application builders - Internet of Things
Executive Summit for ISV & Application builders - Internet of Things
 
Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015
 
Code in the Cloud - December 8th 2014
Code in the Cloud - December 8th 2014Code in the Cloud - December 8th 2014
Code in the Cloud - December 8th 2014
 
Adam azure presentation
Adam   azure presentationAdam   azure presentation
Adam azure presentation
 
release management
release managementrelease management
release management
 
cloud value for application development
cloud value for application developmentcloud value for application development
cloud value for application development
 
Modern lifecycle management practices
Modern lifecycle management practicesModern lifecycle management practices
Modern lifecycle management practices
 
Belgian visual studio launch 2013
Belgian visual studio launch 2013Belgian visual studio launch 2013
Belgian visual studio launch 2013
 
Windows Azure Virtually Speaking
Windows Azure Virtually SpeakingWindows Azure Virtually Speaking
Windows Azure Virtually Speaking
 
Inside the Microsoft TechDays Belgium Apps
Inside the Microsoft TechDays Belgium AppsInside the Microsoft TechDays Belgium Apps
Inside the Microsoft TechDays Belgium Apps
 
TechDays 2013 Developer Keynote
TechDays 2013 Developer KeynoteTechDays 2013 Developer Keynote
TechDays 2013 Developer Keynote
 
Windows Phone 8 Security Deep Dive
Windows Phone 8 Security Deep DiveWindows Phone 8 Security Deep Dive
Windows Phone 8 Security Deep Dive
 
Deep Dive into Entity Framework 6.0
Deep Dive into Entity Framework 6.0Deep Dive into Entity Framework 6.0
Deep Dive into Entity Framework 6.0
 
Applied MVVM in Windows 8 apps: not your typical MVVM session!
Applied MVVM in Windows 8 apps: not your typical MVVM session!Applied MVVM in Windows 8 apps: not your typical MVVM session!
Applied MVVM in Windows 8 apps: not your typical MVVM session!
 
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.jsBuilding SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
 
Deep Dive and Best Practices for Windows Azure Storage Services
Deep Dive and Best Practices for Windows Azure Storage ServicesDeep Dive and Best Practices for Windows Azure Storage Services
Deep Dive and Best Practices for Windows Azure Storage Services
 
Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...
 
Bart De Smet Unplugged
Bart De Smet UnpluggedBart De Smet Unplugged
Bart De Smet Unplugged
 

02 dev room6__tapand_go_jeffprosise_9Tap and Go: Proximity Networking in WinRT

  • 1.
  • 2. A Message from the Team We want to hear from you – app developers! Microsoft will be hosting a live Q&A session via Lync for your company to ask questions, or provide feedback, on the Windows 8 Proximity/NFC APIs. You’ll have an opportunity to communicate directly with product engineers who built the proximity APIs. March 12th from 5 – 6 PM local Belgium time (GMT+1) http://aka.ms/gwevca
  • 3. Near Field Communication (NFC) Enables devices to communicate wirelessly while in close proximity (3 to 4 cm) of each other  "Devices" can be powered or passive (e.g., smart tag) May be used to establish Bluetooth, WiFi, and WiFi Direct connections for non-proximate transfers Supported by many platforms, including Windows 8, Windows Phone 8, Android, and Symbian Standards driven by NFC Forum (160+ members)
  • 4. NFC Modes and Use Cases NFC enables a multitude of "tap and do" scenarios which are intuitive to users and require no setup Read and write Tap devices to establish information stored in peer-to-peer Tap a payment passive NFC tags communication and share terminal to execute ("smart tags") content electronic payments Reader/Writer Mode Peer-to-Peer Mode Card Emulation Mode
  • 5. NFC Data Exchange Format (NDEF) Lightweight, binary, platform-independent format for NFC messages with variable-length payloads Read and write Or store them them with in inductively smartphones powered and other smart tags mobile devices
  • 6. NFC in WinRT Tap For NFC Socket Connection Connection ProximityDevice PeerFinder Exchange NDEF messages and Exchange data using Windows messages using SNEP Bluetooth, WiFi, or WiFi Direct* * WiFi Direct supported in Windows 8 but not Windows Phone 8
  • 7. Proximity Capability Windows apps that use proximity networking must indicate that through their manifests Windows 8 Windows Phone 8
  • 8. The ProximityDevice Class Provides methods for driving NFC devices  Publishing NDEF messages to devices and tags  Subscribing to NDEF messages from devices and tags  Identifying on-board proximity devices Contains properties for retrieving transfer rates and other information about proximity devices Fires events when other proximity devices arrive and depart
  • 9. Detecting NFC Support var device = ProximityDevice.GetDefault(); if (device != null) { // This device supports NFC }
  • 10. Getting Device Information var device = ProximityDevice.GetDefault(); if (device != null) { var id = device.DeviceId; // Device ID var bps = device.BitsPerSecond; // Max transfer rate (bps) var size = device.MaxMessageBytes; // Max message size (bytes) }
  • 11. Detecting Arrivals and Departures var device = ProximityDevice.GetDefault(); if (device != null) { device.DeviceArrived += OnDeviceArrived; device.DeviceDeparted += OnDeviceDeparted; } void OnDeviceArrived(ProximityDevice sender) { // Proximity device arrived } void OnDeviceDeparted(ProximityDevice sender) { // Proximity device departed }
  • 12. PublishMessage ProximityDevice.PublishMessage publishes Windows.subtype messages to other devices  Supported by Windows and Windows Phone  Not supported by other platforms  subtype can be anything you want  Supports transmission of string data  Does not publish to smart tags ProximityDevice.StopPublishingMessage stops publishing a message
  • 13. Using PublishMessage // Publish without a completed callback device.PublishMessage("Windows.Sample", "Hello, NFC!"); // Publish with a completed callback device.PublishMessage("Windows.Sample", "Hello, NFC!", OnMessageTransmitted); . . . void OnMessageTransmitted(ProximityDevice sender, long messageId) { // Stop publishing the message once it's delivered device.StopPublishingMessage(messageId); }
  • 14. Subscribing to Messages ProximityDevice.SubscribeForMessage subscribes to NDEF messages of the specified type  "Windows.subtype" messages  "WindowsUri" messages for URIs  "WriteableTag" messages for writeable tags  "NDEF[:filter]" messages for other message types  e.g., NDEF, NDEF:ext, and NDEF:wkt.U ProximityDevice.StopSubscribingForMessage revokes a message subscription
  • 15. Using SubscribeForMessage device.SubscribeForMessage("Windows.Sample", OnReceived); . . . void OnReceived(ProximityDevice sender, ProximityMessage message) { string type = message.MessageType; // e.g., "Windows.Sample" string data = message.DataAsString; // e.g., "Hello, NFC!" // Do this now, or do it later to continue subscribing device.StopSubscribingForMessage(message.SubscriptionId); }
  • 16.
  • 17. The PeerFinder Class Provides API for establishing socket connections via NFC for direct app- to-app communications  Methods for establishing connections  Properties for feature detection, connecting to other platforms, and exerting control over transport types  Events signifying connection requests TriggeredConnectionStateChanged event makes tap-to-connect gestures simple and easy
  • 18. Detecting Tap-to-Connect Support if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) != 0) { // This device supports tap-to-connect }
  • 19. Establishing a Socket Connection if ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) != 0) { PeerFinder.TriggeredConnectionStateChanged += OnTriggered; PeerFinder.Start(); } void OnTriggered(object sender, TriggeredConnectionStateChangedEventArgs e) { if (e.State == TriggeredConnectState.Completed) { var socket = e.Socket; // StreamSocket PeerFinder.Stop(); } }
  • 20. Triggered Connection State void OnTriggered(object sender, TriggeredConnectionStateChangedEventArgs e) { switch (e.State) { case TriggeredConnectState.Listening: break; case TriggeredConnectState.PeerFound: // OK to move devices apart break; case TriggeredConnectState.Connecting: // Establishing socket connection break; case TriggeredConnectState.Completed: // StreamSocket reference in e.Socket break; case TriggeredConnectState.Canceled: // Connection was closed break; case TriggeredConnectState.Failed: // Connection could not be established break; } }
  • 21. Controlling the Transport Type // All values default to true PeerFinder.AllowBluetooth = true; // Bluetooth PeerFinder.AllowInfrastructure = true; // WiFi PeerFinder.AllowWiFiDirect = true; // WiFi Direct (Win8 only)
  • 22. Alternate (App) Identities PeerFinder.AlternateIdentities enables apps on different platforms to connect to each other  e.g., Windows to Windows Phone In a Windows app, add entry identifying corresponding app on Windows Phone  App ID = {App product ID} In a Windows Phone app, add entry identifying corresponding app on Windows  App ID = {Package family name}!App
  • 23. Enabling Windows Connections PeerFinder.AlternateIdentities.Add( "Windows", // Platform identifier "f5bbba4f-c852-4e33-9e5d-54fe1c732524_ky5brtva589yy!App" );
  • 24. Enabling Windows Phone Connections PeerFinder.AlternateIdentities.Add( "WindowsPhone", // Platform identifier "{b2c65896-3f48-4ea9-8c1c-773a17c38bff}" );
  • 25.
  • 26. PublishBinaryMessage Publishes NDEF messages to devices and tags  WriteTag messages for writing to smart tags  Windows:WriteTag, WindowsUri:WriteTag, LaunchApp:WriteTag, and NDEF:WriteTag  NDEF:WriteTag supports smart posters, Android Application Records (AARs), and more  NDEF messages for publishing to other devices  WindowsMime messages to other devices Use NDEF Library for Proximity APIs for help formatting binary NDEF messages
  • 27. Getting an NFC Tag's Capacity device.SubscribeForMessage("WriteableTag", OnReceived); . . . void OnReceived(ProximityDevice sender, ProximityMessage message) { var size = BitConverter.ToInt32(message.Data.ToArray(), 0); }
  • 28. Writing URIs to NFC Tags using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE }) { writer.WriteString("http://www.wintellect.com"); var buffer = writer.DetachBuffer(); device.PublishBinaryMessage("WindowsUri:WriteTag", buffer); }
  • 29. Writing Windows Launch Tags using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE }) { string tag = "argument" + // Optional launch argument "tWindowst" + // Platform identifier "1ED5AEA5.AngryBirdsSpace_p2gbknwb5d8r2!App"; // App ID writer.WriteString(tag); var buffer = writer.DetachBuffer(); device.PublishBinaryMessage("LaunchApp:WriteTag", buffer); }
  • 30. Writing Windows Phone Launch Tags using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE }) { string tag = "argument" + // Optional launch argument "tWindowsPhonet" + // Platform identifier "{afc3dfcf-8429-4e0d-9df8-4038939b5e75}"; // App ID writer.WriteString(tag); var buffer = writer.DetachBuffer(); device.PublishBinaryMessage("LaunchApp:WriteTag", buffer); }
  • 31. Writing Dual Launch Tags using (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE }) { string tag = "argument" + "tWindowst" + "1ED5AEA5.AngryBirdsSpace_p2gbknwb5d8r2!App" + "tWindowsPhonet" + "{afc3dfcf-8429-4e0d-9df8-4038939b5e75}"; writer.WriteString(tag); var buffer = writer.DetachBuffer(); device.PublishBinaryMessage("LaunchApp:WriteTag", buffer); }
  • 32. Using Launch Arguments (Windows) protected override void OnNavigatedTo(NavigationEventArgs e) { // If this page was activated from an NFC tag or a // secondary tile, retrieve the launch argument if (e.Parameter != null && e.Parameter != String.Empty) { string arg = (string)e.Parameter; // TODO: Use the launch argument } }
  • 33. Using Launch Arguments (Phone) private const string _key = "ms_nfp_launchargs"; . . . protected override void OnNavigatedTo(NavigationEventArgs e) { // If this page was activated from an NFC tag, retrieve the launch argument if (NavigationContext.QueryString.ContainsKey(_key)) { string arg = NavigationContext.QueryString[_key]; // TODO: Use the launch argument } }
  • 34.
  • 35. NDEF Library for Proximity APIs Free, open-source library for reading and writing NDEF messages, including smart posters and AARs Compatible with Windows 8 and WP8
  • 36. Writing a Smart Poster Tag var record = new NdefSpRecord(); record.Uri = "http://www.wintellect.com"; record.NfcAction = NdefSpActRecord.NfcActionType.DoAction; record.AddTitle(new NdefTextRecord { Text = "Wintellect", LanguageCode = "en" }); var message = new NdefMessage { record }; device.PublishBinaryMessage("NDEF:WriteTag", message.ToByteArray().AsBuffer());
  • 37. Reading a Smart Poster Tag device.SubscribeForMessage("NDEF", OnMessageReceived); ... void OnMessageReceived(ProximityDevice sender, ProximityMessage message) { var ndef = NdefMessage.FromByteArray(message.Data.ToArray()); foreach (NdefRecord record in ndef) { if (record.CheckSpecializedType(false) == typeof(NdefSpRecord)) { var poster = new NdefSpRecord(record); var uri = poster.Uri; for (int i = 0; i < poster.TitleCount(); i++) var title = poster.Titles[i].Text; } } }
  • 38. Writing an Android Launch Tag var record = new NdefAndroidAppRecord(); record.PackageName = "com.adobe.reader"; var message = new NdefMessage { record }; device.PublishBinaryMessage("NDEF:WriteTag", message.ToByteArray().AsBuffer());
  • 39.
  • 40. PublishUriMessage Publishes URI messages to other devices  Messages include standard NDEF URI records  Compatible with Windows and non-Windows devices  Only one URI message can be published at a time URI messages launch URIs on target devices  http:// protocol launches browser and shows the specified URL (e.g., http://www.wintellect.com)  Other protocols launch apps registered for those protocols and can include launch parameters Great way to launch apps on other platforms!
  • 41. Launching a Browser var uri = new Uri("http://www.wintellect.com"); device.PublishUriMessage(uri, OnMessageTransmitted); . . . void OnMessageTransmitted(ProximityDevice sender, long messageId) { // Message delivered }
  • 42. Launching Skype var uri = new Uri("skype:lori.prosise?call"); device.PublishUriMessage(uri, OnMessageTransmitted); . . . void OnMessageTransmitted(ProximityDevice sender, long messageId) { // Message delivered }
  • 43. Subscribing to URI Messages device.SubscribeForMessage("WindowsUri", OnUriReceived); . . . private async void OnUriReceived(ProximityDevice sender, ProximityMessage message) { var array = message.Data.ToArray(); var uri = Encoding.Unicode.GetString(array, 0, array.Length); }