Top Banner
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.
47

Windows 8 Platform NFC Development

May 11, 2015

Download

Technology

Andreas Jakl

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
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Windows 8 Platform NFC Development

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.

Page 2: Windows 8 Platform NFC Development

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

Page 3: Windows 8 Platform NFC Development

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

Page 4: Windows 8 Platform NFC Development

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

Page 5: Windows 8 Platform NFC Development

NFC Scenarios

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl

Connect Devices Exchange Digital Objects Acquire Content

5

Page 6: Windows 8 Platform NFC Development

ACQUIRE CONTENTFrom Tags and Peers

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 6

Page 7: Windows 8 Platform NFC Development

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

Page 8: Windows 8 Platform NFC Development

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

Page 9: Windows 8 Platform NFC Development

Proximity Capability

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 9

Page 10: Windows 8 Platform NFC Development

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

Page 11: Windows 8 Platform NFC Development

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

Page 12: Windows 8 Platform NFC Development

SPREAD THE WORDPublish & Write

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 12

Page 13: Windows 8 Platform NFC Development

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

Page 14: Windows 8 Platform NFC Development

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

Page 15: Windows 8 Platform NFC Development

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

Page 16: Windows 8 Platform NFC Development

NDEF HANDLINGStandardized NFC Tag Contents

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 16

Page 17: Windows 8 Platform NFC Development

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

Page 18: Windows 8 Platform NFC Development

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/

Page 19: Windows 8 Platform NFC Development

_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

Page 20: Windows 8 Platform NFC Development

NFC / NDEF LIBRARY FOR PROXIMITY APISWindows 8 & Windows Phone 8

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 20

Page 21: Windows 8 Platform NFC Development

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)

Page 22: Windows 8 Platform NFC Development

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

Page 23: Windows 8 Platform NFC Development

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

Page 24: Windows 8 Platform NFC Development

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());

Page 25: Windows 8 Platform NFC Development

APP LAUNCHING

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 25

Page 26: Windows 8 Platform NFC Development

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

Page 27: Windows 8 Platform NFC Development

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

Page 28: Windows 8 Platform NFC Development

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

Page 29: Windows 8 Platform NFC Development

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

Page 30: Windows 8 Platform NFC Development

User Experience

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 30

No app installed 1 app installed 2+ apps installed

Page 31: Windows 8 Platform NFC Development

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

Page 32: Windows 8 Platform NFC Development

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

Page 33: Windows 8 Platform NFC Development

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."));

Page 34: Windows 8 Platform NFC Development

Windows 8 Protocol Association

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 34

bit.l

y/A

ppLa

unch

ing

Page 35: Windows 8 Platform NFC Development

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*

Page 36: Windows 8 Platform NFC Development

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

Page 37: Windows 8 Platform NFC Development

PEER TO PEER

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 37

Page 38: Windows 8 Platform NFC Development

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

Page 39: Windows 8 Platform NFC Development

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.

Page 40: Windows 8 Platform NFC Development

Tap to Trigger

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 40

App not installed

App installed

Page 41: Windows 8 Platform NFC Development

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)

Page 42: Windows 8 Platform NFC Development

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

Page 43: Windows 8 Platform NFC Development

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

Page 44: Windows 8 Platform NFC Development

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

Page 45: Windows 8 Platform NFC Development

nfcinteractor.com

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 45

Page 46: Windows 8 Platform NFC Development

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

Page 47: Windows 8 Platform NFC Development

Thank You.

Andreas Jakl@mopius

mopius.comnfcinteractor.com

Windows 8 Platform NFC Development v2.0.0 © 2014 Andreas Jakl 47