02 dev room6__tapand_go_jeffprosise_9Tap and Go: Proximity Networking in WinRT

  • 672 views
Uploaded on

More info on http://www.techdays.be

More info on http://www.techdays.be

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
672
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
9
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. 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 toask questions, or provide feedback, on the Windows 8 Proximity/NFCAPIs. You’ll have an opportunity to communicate directly with productengineers who built the proximity APIs. March 12th from 5 – 6 PM local Belgium time (GMT+1) http://aka.ms/gwevca
  • 2. Near Field Communication (NFC)Enables devices to communicate wirelessly while in close proximity (3 to4 cm) of each other "Devices" can be powered or passive (e.g., smart tag)May be used to establish Bluetooth, WiFi, and WiFi Direct connectionsfor non-proximate transfersSupported by many platforms, including Windows 8, Windows Phone8, Android, and SymbianStandards driven by NFC Forum (160+ members)
  • 3. NFC Modes and Use CasesNFC enables a multitude of "tap and do" scenarios which are intuitive tousers 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
  • 4. NFC Data Exchange Format (NDEF)Lightweight, binary, platform-independent format for NFC messages withvariable-length payloads Read and write Or store them them with in inductively smartphones powered and other smart tags mobile devices
  • 5. 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
  • 6. Proximity CapabilityWindows apps that use proximity networking must indicate that throughtheir manifests Windows 8 Windows Phone 8
  • 7. The ProximityDevice ClassProvides methods for driving NFC devices Publishing NDEF messages to devices and tags Subscribing to NDEF messages from devices and tags Identifying on-board proximity devicesContains properties for retrieving transfer rates and other informationabout proximity devicesFires events when other proximity devices arrive and depart
  • 8. Detecting NFC Supportvar device = ProximityDevice.GetDefault();if (device != null){ // This device supports NFC}
  • 9. Getting Device Informationvar 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)}
  • 10. Detecting Arrivals and Departuresvar 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}
  • 11. PublishMessageProximityDevice.PublishMessage publishes Windows.subtype messagesto 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 tagsProximityDevice.StopPublishingMessage stops publishing a message
  • 12. Using PublishMessage// Publish without a completed callbackdevice.PublishMessage("Windows.Sample", "Hello, NFC!");// Publish with a completed callbackdevice.PublishMessage("Windows.Sample", "Hello, NFC!", OnMessageTransmitted); . . .void OnMessageTransmitted(ProximityDevice sender, long messageId){ // Stop publishing the message once its delivered device.StopPublishingMessage(messageId);}
  • 13. Subscribing to MessagesProximityDevice.SubscribeForMessage subscribes to NDEF messagesof 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.UProximityDevice.StopSubscribingForMessage revokes a messagesubscription
  • 14. Using SubscribeForMessagedevice.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);}
  • 15. The PeerFinder ClassProvides 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 requestsTriggeredConnectionStateChanged event makes tap-to-connect gesturessimple and easy
  • 16. Detecting Tap-to-Connect Supportif ((PeerFinder.SupportedDiscoveryTypes & PeerDiscoveryTypes.Triggered) != 0){ // This device supports tap-to-connect}
  • 17. Establishing a Socket Connectionif ((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(); }}
  • 18. Triggered Connection Statevoid 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; }}
  • 19. Controlling the Transport Type// All values default to truePeerFinder.AllowBluetooth = true; // BluetoothPeerFinder.AllowInfrastructure = true; // WiFiPeerFinder.AllowWiFiDirect = true; // WiFi Direct (Win8 only)
  • 20. Alternate (App) IdentitiesPeerFinder.AlternateIdentities enables apps on different platforms toconnect to each other e.g., Windows to Windows PhoneIn a Windows app, add entry identifying corresponding app on WindowsPhone App ID = {App product ID}In a Windows Phone app, add entry identifying corresponding app onWindows App ID = {Package family name}!App
  • 21. Enabling Windows ConnectionsPeerFinder.AlternateIdentities.Add( "Windows", // Platform identifier "f5bbba4f-c852-4e33-9e5d-54fe1c732524_ky5brtva589yy!App");
  • 22. Enabling Windows Phone ConnectionsPeerFinder.AlternateIdentities.Add( "WindowsPhone", // Platform identifier "{b2c65896-3f48-4ea9-8c1c-773a17c38bff}");
  • 23. PublishBinaryMessagePublishes 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 devicesUse NDEF Library for Proximity APIs for help formatting binary NDEFmessages
  • 24. Getting an NFC Tags Capacitydevice.SubscribeForMessage("WriteableTag", OnReceived); . . .void OnReceived(ProximityDevice sender, ProximityMessage message){ var size = BitConverter.ToInt32(message.Data.ToArray(), 0);}
  • 25. Writing URIs to NFC Tagsusing (var writer = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE }){ writer.WriteString("http://www.wintellect.com"); var buffer = writer.DetachBuffer(); device.PublishBinaryMessage("WindowsUri:WriteTag", buffer);}
  • 26. Writing Windows Launch Tagsusing (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);}
  • 27. Writing Windows Phone Launch Tagsusing (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);}
  • 28. Writing Dual Launch Tagsusing (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);}
  • 29. 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 }}
  • 30. 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 }}
  • 31. NDEF Library for Proximity APIsFree, open-source library for reading and writing NDEFmessages, including smart posters and AARsCompatible with Windows 8 and WP8
  • 32. Writing a Smart Poster Tagvar 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());
  • 33. Reading a Smart Poster Tagdevice.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; } }}
  • 34. Writing an Android Launch Tagvar record = new NdefAndroidAppRecord();record.PackageName = "com.adobe.reader";var message = new NdefMessage { record };device.PublishBinaryMessage("NDEF:WriteTag", message.ToByteArray().AsBuffer());
  • 35. PublishUriMessagePublishes 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 timeURI 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 parametersGreat way to launch apps on other platforms!
  • 36. Launching a Browservar uri = new Uri("http://www.wintellect.com");device.PublishUriMessage(uri, OnMessageTransmitted); . . .void OnMessageTransmitted(ProximityDevice sender, long messageId){ // Message delivered}
  • 37. Launching Skypevar uri = new Uri("skype:lori.prosise?call");device.PublishUriMessage(uri, OnMessageTransmitted); . . .void OnMessageTransmitted(ProximityDevice sender, long messageId){ // Message delivered}
  • 38. Subscribing to URI Messagesdevice.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);}