Windows 8 Platform NFC Development Andreas Jakl, Mopius Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 1 NFC Forum and the NFC Forum logo are trademarks of the Near Field Communication Forum.
May 11, 2015
Windows 8 PlatformNFC Development
Andreas Jakl, Mopius
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 1NFC Forum and the NFC Forum logo are trademarks of the Near Field Communication Forum.
Andreas JaklTwitter: @mopius
Email: [email protected]
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
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 3
Based on MSDN documentationbit.ly/ProximityAPIbit.ly/ProximityAPIwp8bit.ly/ProximitySpec
We’re coveringWindows (Phone) 8 Proximity APIs
Tap and Do
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 4
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)
Documentation: bit.ly/ProximitySpec
NFC Scenarios
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl
Connect Devices Exchange Digital Objects Acquire Content
5
ACQUIRE CONTENTFrom Tags and Peers
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 6
Acquire Content Scenarios
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 7
Website link (e.g., company)
More information (e.g., museum, concert)
Custom app extensions (e.g., bonus item for a game)
Angry Birds © Rovio
LaulujoutsenWhooper SwanNational bird of Finland, on €1 coin
Get Started: Read URIs via NFC
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 8
ProximityDeviceConnect to HWDetect devices in rangePublish & subscribe to messages
ProximityMessageContents of received message
Proximity Capability
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 9
URI Subscriptions
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 10
_device = ProximityDevice.GetDefault();
_subscribedMessageId = _device.SubscribeForMessage("WindowsUri", MessageReceivedHandler);
1 Activate proximity device
2 Subscribe to URI messages
3 Handle messagesprivate void MessageReceivedHandler(ProximityDevice sender,
ProximityMessage message) {var msgArray = message.Data.ToArray();var url = Encoding.Unicode.GetString(msgArray, 0, msgArray.Length);Debug.WriteLine("URI: " + url);
}
API documentation: bit.ly/ProximityAPI
URI Subscriptions
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 11
_subscribedMessageId = _device.SubscribeForMessage(…);
_device.StopSubscribingForMessage(_subscribedMessageId);
WindowsUriSmart Poster
URI
4 Cancel subscriptions
API documentation: bit.ly/ProximityAPI
SPREAD THE WORDPublish & Write
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 12
Publish Messages
Proximity devices only
– (doesn’t write tags)
Windows Protocol + URI record
– Encapsulated in NDEF
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 13
_publishingMessageId = _device.PublishUriMessage(new Uri("nfcinteractor:compose"));
1 Start publishing
Contains scheme,
platform & App ID
Write Tags
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 14
1 Prepare & convert datavar dataWriter =
new Windows.Storage.Streams.DataWriter { UnicodeEncoding = Windows.Storage.Streams.
UnicodeEncoding.Utf16LE};
dataWriter.WriteString("nfcinteractor:compose");var dataBuffer = dataWriter.DetachBuffer();
2 Write tag (no device publication)_device.PublishBinaryMessage("WindowsUri:WriteTag", dataBuffer);
Mandatory encoding
bit.ly/PublishTypes
Tag Size?
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 15
1 Subscribe for writable tag info_device.SubscribeForMessage("WriteableTag", MessageReceivedHandler);
2 Check maximum writable tag size in handlervar tagSize = BitConverter.ToInt32(message.Data.ToArray(), 0);Debug.WriteLine("Writeable tag size: " + tagSize);
3 Device HW capabilitiesvar bps = _device.BitsPerSecond; // >= 16kB/svar mmb = _device.MaxMessageBytes; // >= 10kB
API documentation: bit.ly/ProximityAPI
NDEF HANDLINGStandardized NFC Tag Contents
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 16
Data on an NFC Tag
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 17
Stored onNFC Forum Tag
Encapsulated inNDEF Message
Encoded throughNFC Forum
Tag Type Platform
DataNDEF Record(s)
[speech text]
{0450eab3-92…}
Arguments
WindowsPhone app ID
LaunchApp
NDEF = NFC Data Exchange Format, Container image adapted from s_volenszki (Flickr), released under Creative Commons BY-NC 2.0
Reading NDEF
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 18
_subscribedMessageId = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
1 Subscribe to all NDEF messages
2 Parse raw byte array in handler
http://www.nfc-forum.org/specs/
_subscribedMessageId = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
Subscribe to all NDEF messages
Parse raw byte array in handler
http://www.nfc-forum.org/specs/
// Convert the language code to a byte arrayvar languageEncoding = Encoding.UTF8;var encodedLanguage = languageEncoding.GetBytes(languageCode);// Encode and convert the text to a byte arrayvar encoding = (textEncoding == TextEncodingType.Utf8) ? Encoding.UTF8 : Encoding.BigEndianUnicode;var encodedText = encoding.GetBytes(text);// Calculate the length of the payload & create the arrayvar payloadLength = 1 + encodedLanguage.Length + encodedText.Length;Payload = new byte[payloadLength];
// Assemble the status bytePayload[0] = 0; // Make sure also the RFU bit is set to 0// Text encodingif (textEncoding == TextEncodingType.Utf8)
Payload[0] &= 0x7F; // ~0x80else
Payload[0] |= 0x80;
// Language code lengthPayload[0] |= (byte)(0x3f & (byte)encodedLanguage.Length);
// Language codeArray.Copy(encodedLanguage, 0, Payload, 1, encodedLanguage.Length);
// TextArray.Copy(encodedText, 0, Payload, 1 + encodedLanguage.Length, encodedText.Length);Si
mpl
e ex
ampl
e:as
sem
blin
g pa
yloa
d of
Text
reco
rd
Reading NDEF
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 19
1
2
NFC / NDEF LIBRARY FOR PROXIMITY APISWindows 8 & Windows Phone 8
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 20
NDEF.codeplex.com
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 21
Reusable NDEF classes
Create NDEFmessages & records
(standard compliant)
Parse informationfrom raw byte arrays
Fully documentedOpen Source LGPL license
(based on Qt Mobility)
NDEF Subscriptions
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 22
_subscribedMessageId = _device.SubscribeForMessage("NDEF",MessageReceivedHandler);
1 Subscribe to all NDEF formatted tags
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message){
var msgArray = message.Data.ToArray();NdefMessage ndefMessage = NdefMessage.FromByteArray(msgArray);[...]
}
2 Parse NDEF message
NDEF Subscriptions
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 23
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 exampleif (record.CheckSpecializedType(false) == typeof(NdefSpRecord)) {
// Convert and extract Smart Poster infovar 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());
}}
3 Analyze all contained NDEF records with specialized classes
Write NDEF
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 24
1 Prepare & convert data// Initialize Smart Poster record with URI, Action + 1 Titlevar spRecord = new NdefSpRecord
{ Uri = "http://www.nfcinteractor.com" };spRecord.AddTitle(new NdefTextRecord
{ Text = "Nfc Interactor", LanguageCode = "en" });
// Add record to NDEF messagevar 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());
APP LAUNCHING
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 25
App Launch Scenarios
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 26
Discover your app
Share app to other users
Create seamless multi-user experience
Register for
App Launching Summary
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 27
Files
User opensparticular file
URI protocol
Tag launches appthrough custom
URI scheme
LaunchApp Tag
Tag directly containsapp name and
parameters
Peer to Peer
App requests peerdevice to startthe same app
Not so relevant for NFC
How to Launch Apps
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl
Custom URI schemelaunches app.App needs to register.
Tag directly containsapp name andcustom data.No registration necessary.
eith
er o
r
Win8 + WP8
28
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 29
nearspeak: Good+morning.Custom data
Protocol name
Encoded Launch URI
Examples*skype:mopius?call
spotify:search:17th%20boulevard
* Definition & examples: http://en.wikipedia.org/wiki/URI_scheme
User Experience
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 30
No app installed 1 app installed 2+ apps installed
WP Protocol Association
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 31
1 Specify protocol name in WMAppManifest.xml
...</Tokens><Extensions><Protocol Name="nearspeak"
NavUriFragment="encodedLaunchUri=%s"TaskID="_default" />
</Extensions>
Protocol name
Fixed
Note: different in Win8 / WP8
WP Protocol Association
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 32
2 Create UriMapper class to parse parametersclass 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 parametersreturn new Uri("/MainPage.xaml?ms_nfp_launchargs=" + launchContents, UriKind.Relative);
}
// Include the original URI with the mapping to the main pagereturn uri;
}} Argument already handled in step 9 of LaunchApp tags (MainPage.OnNavigatedTo)
Note: different in Win8 / WP8
WP Protocol Association
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 33
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 Protocol Association
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 34
bit.l
y/A
ppLa
unch
ing
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 35
Directly launch App
parameters app name 1platform 1 platform 2 app name 2 …
* 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
Encoded into NDEF message*
Write LaunchApp Tags
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 36
var launchArgs = "user=default"; // Can be empty// The app's product id from the app manifest, wrapped in {}var productId = "{xxx}"; var launchAppMessage = launchArgs + "\tWindowsPhone\t" + productId;
var dataWriter = new Windows.Storage.Streams.DataWriter{UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE};
dataWriter.WriteString(launchAppMessage);
1 Launch parameters, platforms + app IDs (note: Win8/WP8 ID format differences)
2 Convert to byte array
3 Write to tags_device.PublishBinaryMessage("LaunchApp:WriteTag",
dataWriter.DetachBuffer());
Note: different in Win8 / WP8
PEER TO PEER
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 37
Tap for
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 38
Quick Data Exchange
ProximityDeviceExchange Windows /
NDEF messages,SNEP protocol
Long Term Connection
PeerFinderAutomatically builds
Bt / WiFi Directsocket connection
Seamless Multi-User Games & Collaboration
Establishing
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 39
Long Term Connection
Trigger
Interact with TapNFC
Browse
Start SearchBt, WiFi, etc.
Tap to Trigger
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 40
App not installed
App installed
Connection State
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 41
PeerFound
1Proximity gesture completeDevices can be pulled away
Connecting /Listening
2Which device initiated tap gesture?→ Connecting, other device Listening
Completed
3Access socket of persistent transport
(e.g., TCP/IP, Bt)
Find Peers
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 42
PeerFinder.TriggeredConnectionStateChanged +=TriggeredConnectionStateChanged;
PeerFinder.Start();
1 Start waiting for triggered connections
2 Peer found & connection established? Send message over socket
* For URI records + simple Smart Poster (w/o title), use the WindowsUri type.
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();
}}Completed
3
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 43* bit.ly/ProximityUX
NFC ToolsProximity 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
nfcinteractor.com
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 45
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
Thank You.
Andreas Jakl@mopius
mopius.comnfcinteractor.com
Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 47