Windows 8 Platform NFC Development

8 726 vues

Publié le

Introduction to the Windows 8 Platform Proximity APIs for NFC apps.

Create your own Near Field Communication apps to interact with peers as well as NFC tags. Also introduces the open source NDEF Library for Proximity APIs: http://ndef.codeplex.com/

- Subscribe to proximity messages
- Publish messages to peers and tags (WindowsUri and NDEF records)
- Parse & create NDEF messages (including Smart Posters)
- Launching apps on own and peer devices
- Registering for custom URI schemes and protocols
- LaunchApp tags to directly start the app
- Peer to peer: quick data exchange and long term connections with Wi-Fi Direct / Bluetooth
- Establishing peer to peer socket communications simply by tapping two devices
- User Experience Recommendations for peer to peer apps

Publié dans : Technologie
3 commentaires
11 j’aime
Statistiques
Remarques
Aucun téléchargement
Vues
Nombre de vues
8 726
Sur SlideShare
0
Issues des intégrations
0
Intégrations
67
Actions
Partages
0
Téléchargements
206
Commentaires
3
J’aime
11
Intégrations 0
Aucune incorporation

Aucune remarque pour cette diapositive

Windows 8 Platform NFC Development

  1. 1. Windows 8 Platform NFC Development Andreas Jakl, Mopius Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl NFC Forum and the NFC Forum logo are trademarks of the Near Field Communication Forum. 1
  2. 2. Andreas Jakl Twitter: @mopius Email: andreas.jakl@mopius.com Trainer & app developer – mopius.com – nfcinteractor.com Nokia: Technology Wizard FH Hagenberg, Mobile Computing: Assistant Professor Siemens / BenQ Mobile: Augmented Reality-Apps Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 2
  3. 3. We’re covering Windows (Phone) 8 Proximity APIs Based on MSDN documentation bit.ly/ProximityAPI bit.ly/ProximityAPIwp8 bit.ly/ProximitySpec Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 3
  4. 4. Tap and Do A gesture that is a natural interaction between people in close proximity used to trigger doing something together between the devices they are holding. System: Near Field Proximity (e.g., NFC) Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl Documentation: bit.ly/ProximitySpec 4
  5. 5. NFC Scenarios Connect Devices Exchange Digital Objects Acquire Content Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 5
  6. 6. From Tags and Peers ACQUIRE CONTENT Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 6
  7. 7. Acquire Content Scenarios Website link (e.g., company) Laulujoutsen Whooper Swan National bird of Finland, on €1 coin More information (e.g., museum, concert) Custom app extensions (e.g., bonus item for a game) Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl Angry Birds © Rovio 7
  8. 8. Get Started: Read URIs via NFC ProximityDevice Connect to HW Detect devices in range Publish & subscribe to messages ProximityMessage Contents of received message Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 8
  9. 9. Proximity Capability Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 9
  10. 10. URI Subscriptions 1 Activate proximity device _device = ProximityDevice.GetDefault(); 2 Subscribe to URI messages _subscribedMessageId = _device.SubscribeForMessage( "WindowsUri", MessageReceivedHandler); 3 Handle messages private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message) { var msgArray = message.Data.ToArray(); var url = Encoding.Unicode.GetString(msgArray, 0, msgArray.Length); Debug.WriteLine("URI: " + url); } Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl API documentation: bit.ly/ProximityAPI 10
  11. 11. URI Subscriptions Smart Poster WindowsUri URI 4 Cancel subscriptions _subscribedMessageId = _device.SubscribeForMessage(…); _device.StopSubscribingForMessage(_subscribedMessageId); Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl API documentation: bit.ly/ProximityAPI 11
  12. 12. Publish & Write SPREAD THE WORD Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 12
  13. 13. Publish Messages 1 Start publishing _publishingMessageId = _device.PublishUriMessage( new Uri("nfcinteractor:compose")); Proximity devices only – (doesn’t write tags) Contains scheme, platform & App ID Windows Protocol + URI record – Encapsulated in NDEF Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 13
  14. 14. Write Tags 1 Prepare & convert data var dataWriter =  new Windows.Storage.Streams.DataWriter {  UnicodeEncoding = Windows.Storage.Streams. UnicodeEncoding.Utf16LE}; dataWriter.WriteString("nfcinteractor:compose"); var dataBuffer = dataWriter.DetachBuffer(); Mandatory encoding 2 Write tag (no device publication) _device.PublishBinaryMessage("WindowsUri:WriteTag", dataBuffer); bit.ly/PublishTypes Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 14
  15. 15. Tag Size? 1 Subscribe for writable tag info _device.SubscribeForMessage("WriteableTag",  MessageReceivedHandler); 2 Check maximum writable tag size in handler var tagSize = BitConverter.ToInt32(message.Data.ToArray(), 0); Debug.WriteLine("Writeable tag size: " + tagSize); 3 Device HW capabilities var bps = _device.BitsPerSecond; var mmb = _device.MaxMessageBytes; // >= 16kB/s // >= 10kB Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl API documentation: bit.ly/ProximityAPI 15
  16. 16. Standardized NFC Tag Contents NDEF HANDLING Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 16
  17. 17. Data on an NFC Tag LaunchApp Arguments [speech text] WindowsPhone app ID {0450eab3-92…} Data NDEF Record(s) Encapsulated in NDEF Message Encoded through NFC Forum Tag Type Platform Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl NDEF = NFC Data Exchange Format, Container image adapted from s_volenszki (Flickr), released under Creative Commons BY-NC 2.0 Stored on NFC Forum Tag 17
  18. 18. Reading NDEF 1 Subscribe to all NDEF messages _subscribedMessageId = _device.SubscribeForMessage( "NDEF", MessageReceivedHandler); 2 Parse raw byte array in handler  http://www.nfc-forum.org/specs/ Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 18
  19. 19. Reading NDEF // Convert the language code to a byte array Simple example: assembling payload of Text record 1 Subscribe to all NDEF messages= Encoding.UTF8; var languageEncoding var encodedLanguage = languageEncoding.GetBytes(languageCode); // Encode and convert the text to a byte array var encoding = (textEncoding == TextEncodingType.Utf8) ? Encoding.UTF8 : Encoding.BigEndianUnicode; var encodedText = encoding.GetBytes(text); // Calculate the length of the payload & create the array var payloadLength = 1 + encodedLanguage.Length + encodedText.Length; Payload = new byte[payloadLength]; _subscribedMessageId = _device.SubscribeForMessage( "NDEF", MessageReceivedHandler); 2 Parse raw byte array in handler  // Assemble the status byte Payload[0] = 0; // Make sure also the RFU bit is set to 0 // Text encoding if (textEncoding == TextEncodingType.Utf8) Payload[0] &= 0x7F; // ~0x80 else Payload[0] |= 0x80; http://www.nfc-forum.org/specs/ // Language code length Payload[0] |= (byte)(0x3f & (byte)encodedLanguage.Length); // Language code Array.Copy(encodedLanguage, 0, Payload, 1, encodedLanguage.Length); // Text Array.Copy(encodedText, 0, Payload, 1 + encodedLanguage.Length, encodedText.Length); Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 19
  20. 20. Windows 8 & Windows Phone 8 NFC / NDEF LIBRARY FOR PROXIMITY APIS Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 20
  21. 21. NDEF.codeplex.com Create NDEF messages & records (standard compliant) Reusable NDEF classes Parse information from raw byte arrays Fully documented Open Source LGPL license (based on Qt Mobility) Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 21
  22. 22. NDEF Subscriptions 1 Subscribe to all NDEF formatted tags _subscribedMessageId = _device.SubscribeForMessage("NDEF", MessageReceivedHandler); 2 Parse NDEF message private void MessageReceivedHandler(ProximityDevice sender,  ProximityMessage message) { var msgArray = message.Data.ToArray(); NdefMessage ndefMessage = NdefMessage.FromByteArray(msgArray); [...] } Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 22
  23. 23. NDEF Subscriptions 3 Analyze all contained NDEF records with specialized classes foreach (NdefRecord record in ndefMessage)  { Debug.WriteLine("Record type: " +  Encoding.UTF8.GetString(record.Type, 0, record.Type.Length)); // Check the type of each record ‐ handling a Smart Poster in this example if (record.CheckSpecializedType(false) == typeof(NdefSpRecord))  { // Convert and extract Smart Poster info var spRecord = new NdefSpRecord(record); Debug.WriteLine("URI: " + spRecord.Uri); Debug.WriteLine("Titles: " + spRecord.TitleCount()); Debug.WriteLine("1. Title: " + spRecord.Titles[0].Text); Debug.WriteLine("Action set: " + spRecord.ActionInUse()); } } Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 23
  24. 24. Write NDEF 1 Prepare & convert data // Initialize Smart Poster record with URI, Action + 1 Title var spRecord = new NdefSpRecord { Uri = "http://www.nfcinteractor.com" }; spRecord.AddTitle(new NdefTextRecord { Text = "Nfc Interactor", LanguageCode = "en" }); // Add record to NDEF message var msg = new NdefMessage { spRecord }; 2a Write tag // Publish NDEF message to a tag _device.PublishBinaryMessage("NDEF:WriteTag", msg.ToByteArray().AsBuffer()); 2b Publish to devices // Alternative: send NDEF message to another NFC device _device.PublishBinaryMessage("NDEF", msg.ToByteArray().AsBuffer()); Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 24
  25. 25. APP LAUNCHING Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 25
  26. 26. App Launch Scenarios Discover your app Share app to other users Create seamless multi-user experience Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 26
  27. 27. App Launching Summary Register for Files URI protocol LaunchApp Tag Peer to Peer User opens particular file Tag launches app through custom URI scheme Tag directly contains app name and parameters App requests peer device to start the same app Not so relevant for NFC Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 27
  28. 28. How to Launch Apps either or Win8 + WP8 Tag directly contains app name and custom data. No registration necessary. Custom URI scheme launches app. App needs to register. Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 28
  29. 29. nearspeak: Good+morning. Protocol name Custom data Encoded Launch URI Examples* skype:mopius?call spotify:search:17th%20boulevard Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl * Definition & examples: http://en.wikipedia.org/wiki/URI_scheme 29
  30. 30. User Experience No app installed 1 app installed 2+ apps installed Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 30
  31. 31. WP Protocol Association Note: different in Win8 / WP8 1 Specify protocol name in WMAppManifest.xml ...</Tokens> Protocol <Extensions> name <Protocol Name="nearspeak" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" /> Fixed </Extensions> Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 31
  32. 32. WP Protocol Association Note: different in Win8 / WP8 2 Create UriMapper class to parse parameters class NearSpeakUriMapper : UriMapperBase { public override Uri MapUri(Uri uri) { // Example: "Protocol?encodedLaunchUri=nearspeak:Good+morning." var tempUri = HttpUtility.UrlDecode(uri.ToString()); var launchContents = Regex.Match(tempUri, @"nearspeak:(.*)$").Groups[1].Value; if (!String.IsNullOrEmpty(launchContents)) { // Launched from associated "nearspeak:" protocol // Call MainPage.xaml with parameters return new Uri("/MainPage.xaml?ms_nfp_launchargs=" + launchContents, UriKind.Relative); } // Include the original URI with the mapping to the main page return uri; }} Argument already handled in step 9 of LaunchApp tags (MainPage.OnNavigatedTo) Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 32
  33. 33. WP Protocol Association 3 Use UriMapper in App.xaml.cs (region: ) private void InitializePhoneApplication() { RootFrame = new PhoneApplicationFrame(); RootFrame.UriMapper = new NearSpeakUriMapper(); } – If needed: launch protocol from app (for app2app comm) await Windows.System.Launcher.LaunchUriAsync( new Uri("nearspeak:Good+morning.")); Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 33
  34. 34. bit.ly/AppLaunching Windows 8 Protocol Association Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 34
  35. 35. parameters platform 1 app name 1 platform 2 app name 2 … Encoded into NDEF message* Directly launch App Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl * For your low-level interest: type: Absolute URI, type name format: windows.com/LaunchApp. Contents re-formatted, e.g., with string lengths before each value 35
  36. 36. Write LaunchApp Tags Note: different in Win8 / WP8 1 Launch parameters, platforms + app IDs (note: Win8/WP8 ID format differences) var launchArgs = "user=default";   // Can be empty // The app's product id from the app manifest, wrapped in {} var productId = "{xxx}";  var launchAppMessage = launchArgs + "tWindowsPhonet" + productId; 2 Convert to byte array var dataWriter = new Windows.Storage.Streams.DataWriter {UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE};    dataWriter.WriteString(launchAppMessage);  3 Write to tags _device.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer()); Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 36
  37. 37. PEER TO PEER Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 37
  38. 38. Seamless MultiUser Games & Collaboration Tap for Quick Data Exchange Long Term Connection ProximityDevice PeerFinder Exchange Windows / NDEF messages, SNEP protocol Automatically builds Bt / WiFi Direct socket connection Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 38
  39. 39. Establishing Trigger Long Term Connection Browse Interact with Tap Start Search NFC Bt, WiFi, etc. Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 39
  40. 40. Tap to Trigger App not installed App installed Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 40
  41. 41. Connection State Proximity gesture complete Devices can be pulled away Which device initiated tap gesture? → Connecting, other device Listening 1 PeerFound 2 Connecting / Listening Access socket of persistent transport (e.g., TCP/IP, Bt) 3 Completed Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 41
  42. 42. Find Peers 1 Start waiting for triggered connections PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged; PeerFinder.Start(); 2 Peer found & connection established? Send message over socket private async void TriggeredConnectionStateChanged(object sender,  TriggeredConnectionStateChangedEventArgs eventArgs) { if (eventArgs.State == TriggeredConnectState.Completed) { // Socket connection established! var dataWriter = new DataWriter(eventArgs.Socket.OutputStream); dataWriter.WriteString("Hello Peer!"); var numBytesWritten = await dataWriter.StoreAsync(); 3 }} Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl * For URI records + simple Smart Poster (w/o title), use the WindowsUri type. 42 Completed
  43. 43. UX Recommendations* User initiated peer search only Ask for consent Show connection state Failed connection? Inform & revert to single-user mode Let user get out of proximity experience Proximity: only if connection details not relevant Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl * bit.ly/ProximityUX 43
  44. 44. NFC Tools Proximity Tapper for WP emulator – http://proximitytapper.codeplex.com/ Open NFC Simulator – http://open-nfc.org/wp/editions/android/ NFC plugin for Eclipse: NDEF Editor – https://code.google.com/p/nfc-eclipse-plugin/ Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 44
  45. 45. nfcinteractor.com Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 45
  46. 46. NFC Resources  NFC News: nfcworld.com  NFC developer comparison (WP, Android, BlackBerry): bit.ly/NfcDevCompare  Specifications: nfc-forum.org Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 46
  47. 47. Thank You. Andreas Jakl @mopius mopius.com nfcinteractor.com Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 47

×