You are on page 1of 99

NFC and Qt Mobility for NFC

Manikantan Krishnamurthy
Technical Manager Nokia, SEAP

2011 Nokia Nokia NFC Development v. 1.1.6 NFC Forum and the NFC Forum logo are trademarks of the Near Field Communication Forum.

What is Near Field Communication (NFC)?


Short-range radio technology that enables communication between devices that touch/momentarily held close together Open-platform technology that is being standardized in the NFC Forum Based on and extends RFID. Operates on 13.56 MHz frequency. Transmits up to 424Kbits/sec Operates over a distance of just a few centimetres, up to 10cm (Nokia: best to touch) Simplifies local communication into an easy and intuitive gesture Typical applications are in contactless transactions, social and local interactions

Extensive experience in NFC globally


First to bring commercial NFC devices to market More than 80 trials and pilots globally (AT&T, O2, Citibank, Maxis, Visa, MasterCard) First to deploy commercial services (Austria, Malaysia, India)

2005
Nokia 5140i
3

2007
Nokia 3220 Nokia 6131 NFC

2008
Nokia 6212 classic

P6/2011
Nokia C7 Symbian Anna

Key NFC Experiences


Service Initiation Sharing
Transfer content between any two NFC devices
Peer to peer mode

Start a service or an application


Reader/writer mode

Pairing
Connect easily with other NFC devices
Reader mode
4

Secure NFC
Mobile device is a credit card and travel card
Card emulation mode

What can NFC do for your App?


Add value (NFC enhanced apps) vs. Create new value (NFC centric apps)

NFC Application Types


NFC Centric Apps
The application will only work

NFC Enhanced Apps


Offer NFC feature when

on NFC devices.
Publisher makes sure that the application is only available to NFC enabled devices

available on device
Check for presence of NFC feature and adapt the user experience or... Make 2 versions of the application

NFC Enhanced App Angry Birds Magic

Comes with 20 levels


First 5 levels available for play Remaining 15 levels are locked Unlock 5 levels at a time with NFC interaction Touch your C7 with another C7 or certain NFC tags

NFC Centric App Poken


Poken is a social networking app that enables exchanging social business cards with a touch
Create your social identity with multiple profiles Auto-friending on social networks such as FB, LinkedIn Combines activity feeds

Collect, classify and share NFC tag info View contacts and collection in a dynamic timeline
8

NFC Basics

http://www.nfc-forum.org/specs/
9

Near Field Communication


International standard
Interface and protocol for simple wireless interconnection of

closely coupled devices operating at 13.56 MHz

Spec overview
Omits specific bit / byte encodings,
details and alternatives Gives high-level overview of the concepts!
10 The 'N' Logo is a trademark of the NFC Forum, Inc. in the United States and in other countries.

NFC Forum Standard Overview *


Applications
Card Emulation
Smart Card capability for mobile devices
Protocol bindings (IP, OBEX, etc)

Reader / Writer
RTD (Record Type Definition) NDEF (NFC Data Exchange format)
Tag Type 1, 2, 3, 4

Peer-2-Peer
LLCP (Logical Link Control Protocol) NFCIP

Mode Switching RF Layer ISO 18092 + ISO 14443 A/B + FeliCa


11 * Figure adapted from NFC Forum Specification (www.nfc-forum.org)

Operating Modes
Reader/writer: when reader is polling for a tag Peer to Peer: communicate with another NFC device (share information) Card Emulation*: where the NFC device acts as a card (e.g. credit card or gift card)
Card Emulation*
Reader /writer

NFC Applications NFC Interfaces

Peer to Peer

Services & adaptation Base Band


NFC Antenna

NFC Controller

* not supported in Symbian Anna


12

Tag & Reader


NFC-based communication between two devices is possible when one device acts as a reader/writer and the other as a tag.

Tag (Initiator)
Simple, thin device containing antenna and small amount of memory Passive, powered by magnetic field that can

Reader (Target) Active device generating radio signals to communicate with tags

Powers the passive tag when the two are


engaged in the passive mode

be picked up by Target
Can be Read-Only/Rewritable/Writable once
13

Discover Services and Content


Touch a hot spot on a smart poster with your device
What is a smart poster or object?
Any object which contains readable NFC tags

Poster

Magazine page

Gadgets

What can NFC tags contain? *


Business card An SMS message Website URL Bluetooth information Code to launch an app

Interactive, immersive and immediate


14 * Additional content types are possible as well.

NFC tags vs. Barcodes

Works by touching, instant Design can be merged with product Larger data storage possible Multiple use cases (app launch, BT pairing) Re-writable (if desired)

No NFC HW required Easily recognizable

Requires NFC HW New to consumers

Inconvenient (camera, focus, take picture) Large visual impact on product Very limited data storage Limited use cases (no app launch, BT pairing) Write-only

15

Developing NFC apps in Qt

16

Target NFC devices


Nokia 600

Nokia 700

Nokia 603 Nokia 701 N9

17

2011 Nokia Nokia NFC Development v. 1.1.6

Following slides are for Qt SDK 1.1.3

24

2011 Nokia Nokia NFC Development v. 1.1.6 August 16, 2011

Qt NFC Development
Requirements
Qt SDK 1.1.3
Contains: Qt 4.7.3, Qt Mobility 1.1.3 Contains: Qt 4.7.4, Qt Mobility 1.2.0

Nokia Ovi Suite 3.x Symbian


Windows 7 (or XP) Nokia C7 with Symbian Anna (for development) Simulator

MeeGo
Nokia N9 Install Qt SDKs experimental MeeGo Harmattan target
25 2011 Nokia Nokia NFC Development v. 1.1.6

Device Setup
Install Symbian Belle (Windows Start menu) Qt 4.7.4

WebKit for Qt 4.7.4


CODA Qt mobility1.2.0

One-click install from Windows requires Ovi Suite


Alternative: copy files to device mass memory, install on the device using Applications Office File mgr.
26 2011 Nokia Nokia NFC Development v. 1.1.6

Qt Mobility
Mobility 1.0 Bearer Management API Contacts Location Messaging Multimedia Publish and Subscribe Service Framework Sensors System Information Versit Mobility 1.1 Camera Document Gallery Feedback Landmarks Maps/Navigation Organizer Service Framework Out of process Mobility 1.2 develop now, deploy later this year Connectivity (Bluetooth, NFC)

27

2011 Nokia Nokia NFC Development v. 1.1.6

Qt Mobility 1.2 NFC


Interact with
NFC Forum tags
Target detection NDEF message handlers Reading and writing NDEF messages Send tag specific commands Master / slave communication

NFC Forum devices


LLCP Sockets Peer to peer communication
28 2011 Nokia Nokia NFC Development v. 1.1.6

API Overview*
* Not a class diagram, but explains sequential usage order

QNearFieldManager
Detects and filters targets

Listen for new server socket connections.

QLlcpServer

Collection of 0 or more records

QNdefMessage

Query properties, read/write messages, send commands or establish a client socket

QNearFieldTarget

Read / write data. For server & client sockets.

QLlcpSocket

Access to NDEF data. Subclasses for handling specific details.


29 2011 Nokia Nokia NFC Development v. 1.1.6

QNdefRecord

Generic NFC Tag access Peer to peer

Qt NFC Source Code


Qt Mobility is Open Source
How does a method work? How to make best use of it? Take a look at the source code!

Download complete source package


http://labs.qt.nokia.com/2011/04/12/qt-mobility1-2-beta-package-released/ qt-mobility-symbian-opensource-1.2.0-beta1.zip Find implementation in: C:\QtMobility\src\connectivity\nfc
30 2011 Nokia Nokia NFC Development v. 1.1.6

https://projects.developer.nokia.com/nfccorkboards

NFC Corkboards

Tasks Extend Qt SDK example with NFC: Touch tag to create note Qt Quick based UI C++ based NFC Integrate C++ with QML

31

2011 Nokia Nokia NFC Development v. 1.1.6

Importing the Example


From Qt Creator
Open project: C:\QtSDK\Examples\4.7\declarative\toys\corkboards\corkboards.pro

32

2011 Nokia Nokia NFC Development v. 1.1.6

Choosing Targets
If you are using SDK 1.1.2, Select our new Qt 4.7.3 for Symbian^3 with QtM1.2b target

33

2011 Nokia Nokia NFC Development v. 1.1.6

Choosing Targets
If you are using SDK 1.1.3,
Select Qt Simulator

34

2011 Nokia Nokia NFC Development v. 1.1.6

Test! With Simulator


Select Qt Simulator Play to compile and deploy!

35

2011 Nokia Nokia NFC Development v. 1.1.6

App Overview

We will add this:


ndefmanager.cpp/.h
NFC Tag discovery and reading

main.cpp
Application startup Loads and shows corkboards.qml
36

corkboards.qml
UI definition Defines data model and view

Day.qml
Delegate for drawing the UI for a single day Interaction for notes

2011 Nokia Nokia NFC Development v. 1.1.6

Model, View & Delegate


ListModel
Defines free-form list data source Container for ListElement definitions

ListView
Shows data from a model in a list Horizontal or vertical

Delegate
Template defining each item instantiated by the view

in: corkboards.qml id: list

in: corkboards.qml id: flickable

in: Day.qml

37

2011 Nokia Nokia NFC Development v. 1.1.6

Add Connectivity
Edit the Qt project file (corkboards.pro)
Uncomment & add mobility component: connectivity
CONFIG += mobility MOBILITY += connectivity

Add LocalServices Capability


symbian:TARGET.CAPABILITY += NetworkServices LocalServices
Allows Internet access Allows NFC

38

2011 Nokia Nokia NFC Development v. 1.1.6

Good to Know: Symbian Security *


* Qt apps are native apps; therefore, the security model of the target operating system applies.

1. Determine the required security / privacy related features


Most common:
Feature
Internet access, telephony, messaging Access location (GPS, etc.) Camera, record audio Contacts, Calendar Bluetooth, NFC IMEI, model name, battery status

(See: developer.nokia.com/Community/Wiki/Capabilities)
Capability
NetworkServices Location UserEnvironment ReadUserData / WriteUserData LocalServices ReadDeviceData

Basic Capabilities

Extended Capabilities

2. Define the capabilities in the Qt project file (.pro)


symbian:TARGET.CAPABILITY += Location LocalServices
39 2011 Nokia Nokia NFC Development v. 1.1.6

Access
Capability
LocalServices ReadUserData WriteUserData NetworkServices UserEnvironment Location
SwEvent ProtServ TrustedUI PowerMgmt SurroundingsDD ReadDeviceData WriteDeviceData CommDD DiskAdmin MultimediaDD NetworkControl AllFiles DRM

User Grantable

Open Signed without PublisherID

Open Signed with PublisherID

Express Signed

V#-Filename.ppt / 10/25/2011 2009 Nokia 40 Symbian

Certified Signed

Signed for Nokia

For testing & sales version

Sales version

For testing

Sales version

Device

Manufacturer
approval

For testing

Sales version

TCB

Lead-time
Note

Immediate
Developer Tested

Immediate
Upload SIS

Immediate
Certify on PC

Immediate
Developer tested

Test house Tested

1 week

Test house Tested

1 week

Good to Know: Symbian Security


3. Get the right certificate during development
No / Basic Capabilities
Use auto-generated self signed certificate
(default, no action required)

Extended Capabilities
Sign up for Ovi Publish account (1)
publish.ovi.com

developer.nokia.com/Distribute/Packaging_and_signing.xhtml

Request development certificate (free)

(Qt Creator build settings)

Sign your app

Test on your develoment device(s)


41 2011 Nokia Nokia NFC Development v. 1.1.6

Good to Know: Symbian Security


4. Publish
No / Basic Capabilities Extended Capabilities
Sign up for Ovi Publish account (1)
publish.ovi.com

developer.nokia.com/Distribute/Packaging_and_signing.xhtml

Request development certificate (free)

Sign & package your Qt app with the Smart Installer


(Qt Creator build settings)

Need Certified Signed capabilities? Publish developer.nokia.com/Community/Wiki/Capabilities -> Purchase a Publisher ID ($200 / year) Submit to Certified Signed process @ www.symbiansigned.com
42 2011 Nokia Nokia NFC Development v. 1.1.6

to the Nokia Store

NdefManager
New C++ class
Right-click the project

Add New ...


C++ Class

Class name: NdefManager


Base class: QObject

43

2011 Nokia Nokia NFC Development v. 1.1.6

Qt Meta-Object System
C++ extended with QObject
Introspection: meta-information at runtime

Inter-object communication: signals & slots


Parent / Child hierarchy: easier memory

management

44

2011 Nokia Nokia NFC Development v. 1.1.6

Include
Headers, define member variable
ndefmanager.h
#include <qnearfieldmanager.h> #include <qndeffilter.h> #include <qnearfieldtarget.h> #include <qndefmessage.h> #include <qndefrecord.h> #include <qndefnfcurirecord.h> #include <QUrl> #include <QDebug> // we will test first! QTM_USE_NAMESPACE // Use Qt Mobility namespace [...] private: QNearFieldManager *nfcManager;
45 2011 Nokia Nokia NFC Development v. 1.1.6

Start Waiting
ndefmanager.cpp
NdefManager::NdefManager(QObject *parent) : QObject(parent) { // NdefManager (this) is the parent; will automatically delete nfcManager nfcManager = new QNearFieldManager(this); nfcManager->setTargetAccessModes(QNearFieldManager::NdefReadTargetAccess); // React only to Uri records (NfcRtd, "U") QNdefFilter filter; filter.appendRecord<QNdefNfcUriRecord>(); // Registers message handler with criteria - Uri nfcManager->registerNdefMessageHandler(filter, this, SLOT(targetDetected(QNdefMessage,QNearFieldTarget*))); // Get notified when the tag gets out of range connect(nfcManager, SIGNAL(targetLost(QNearFieldTarget*)), this, SLOT(targetLost(QNearFieldTarget*))); }46
2011 Nokia Nokia NFC Development v. 1.1.6

Signals & Slots


Signal
Emitted when a particular event occurs (e.g., clicked()) Qt objects: predefined signals Also create your own signals

Slot
Function called in response to a signal Qt objects: predefined slots (e.g., quit()) Also create your own slots

Connection signals slots established by developer, handled by Qt framework


47 2011 Nokia Nokia NFC Development v. 1.1.6

Signals & Slots


Type safe
Signal signature must match signature of receiving slot (Slot might also have shorter signature and ignore the rest of the arguments)

Loosely coupled
Emitter doesnt know or care which slots receive signal Information encapsulation

Integrated, independent components


Slots are normal C++ member functions Dont know if signals are connected to them
48 2011 Nokia Nokia NFC Development v. 1.1.6

Lost & Found


Methods to handle lost & found tags = Slots
ndefmanager.h
private slots: void targetDetected(const QNdefMessage &message, QNearFieldTarget *target); void targetLost(QNearFieldTarget *target);

Tip
Alt + Enter, and Qt Creator writes the .cpp method definition!

49

2011 Nokia Nokia NFC Development v. 1.1.6

React
New target: write debug output to console for now
ndefmanager.cpp
void NdefManager::targetDetected(const QNdefMessage &message, QNearFieldTarget *target) { qDebug() << "Uri Target detected!"; }

Target out of range: delayed object delete


ndefmanager.cpp
void NdefManager::targetLost(QNearFieldTarget *target) { target->deleteLater(); }
50 2011 Nokia Nokia NFC Development v. 1.1.6

Register C++ with QML


Make your C++ class available in QML
QML Name: NdefManager

QML Library: Nfc 1.0


main.cpp
#include <QtDeclarative> #include "ndefmanager.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); qmlRegisterType<NdefManager>("Nfc", 1, 0, "NdefManager"); [...] }
51 2011 Nokia Nokia NFC Development v. 1.1.6

NdefManager in QML
Import module
corkboards.qml
import Nfc 1.0

Create Instance
corkboards.qml
NdefManager { id: ndefManager }

52

2011 Nokia Nokia NFC Development v. 1.1.6

Test! #2
Run the app Touch a URI formatted NDEF tag

Observe the Application Output

53

2011 Nokia Nokia NFC Development v. 1.1.6

Parse Tag & Emit Contents


Revisit and extend the target detection slot
ndefmanager.cpp
void NdefManager::targetDetected(const QNdefMessage &message, QNearFieldTarget *target) { qDebug() << "Uri Target detected!"; // Go through all records in the message foreach (const QNdefRecord &record, message) { // Check type again, just to make sure if (record.isRecordType<QNdefNfcUriRecord>()) { // Convert to the specialized URI record class QNdefNfcUriRecord uriRecord(record); // Emit a signal with the URI emit nfcReadTagUri(uriRecord.uri()); } } }
54 2011 Nokia Nokia NFC Development v. 1.1.6

Define the Signal


Signals have no implementation
They represent information, not a method to execute
ndefmanager.h
signals: void nfcReadTagUri(const QUrl& nfcTagUri);

55

2011 Nokia Nokia NFC Development v. 1.1.6

Create new Notes


Handle our new signal on<signal> : <javascript code>
Get current corkboard page append new notes element
key: noteText, value: URI from NDEF message
corkboards.qml
NdefManager { id: ndefManager onNfcReadTagUri: list.get(flickable.currentIndex).notes.append({"noteText":nfcTagUri}) }
56 2011 Nokia Nokia NFC Development v. 1.1.6

Test! #3
Touch Uri-formatted NDEF NFC tags to create notes on the current page!

57

2011 Nokia Nokia NFC Development v. 1.1.6

Interactive NFC Corkboards


https://projects.developer.nokia.com/nfccorkboards

Tasks Extend previous example React to any kind of tags Write tags by pressing the red flag while touching a tag

58

2011 Nokia Nokia NFC Development v. 1.1.6

Overview Before
Register NDEF filters and detect targets

QNdefFilter filter; filter.appendRecord<QNdefNfcUriRecord>(); nfcManager->registerNdefMessageHandler(filter, this, SLOT(targetDetected(QNdefMessage,QNearFieldTarget*)));

Signal is only emitted when a tag containing all records defined in the filter are found

The slot directly gets the NDEF message

void targetDetected(const QNdefMessage &message, QNearFieldTarget *target);

59

2011 Nokia Nokia NFC Development v. 1.1.6

Overview After
Detect any kind of targets

connect(nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)), this, SLOT(targetDetected(QNearFieldTarget*))); nfcManager->startTargetDetection();


Signals is emitted for every target that is detected

void targetDetected(QNearFieldTarget *target) { const bool hasNdefMessage = target->hasNdefMessage(); if (hasNdefMessage) { connect(target, SIGNAL(ndefMessageRead(QNdefMessage)), this, SLOT(ndefMessageRead(QNdefMessage))); target->readNdefMessages(); } }
Another signal is emitted when reading the message from the target is finished

void NdefManager::ndefMessageRead(const QNdefMessage &message) ;


60 2011 Nokia Nokia NFC Development v. 1.1.6

React to all targets


Generic target detection instead of listening to specific tag message(s)
Remove previous targetDetected() with two parameters
ndefmanager.h
public slots: void nfcWriteTag(const QString& nfcTagText); private slots: void targetDetected(QNearFieldTarget *target); void ndefMessageRead(const QNdefMessage &message); private: QNearFieldTarget *cachedTarget;
61 2011 Nokia Nokia NFC Development v. 1.1.6

// New // Modified from prev. // New // New

Start Generic Target Detection


ndefmanager.cpp
NdefManager::NdefManager(QObject *parent) : QObject(parent) { // [...] // React only to Uri records (NfcRtd, "U") QNdefFilter filter; filter.appendRecord<QNdefNfcUriRecord>(); nfcManager->registerNdefMessageHandler(filter, this, SLOT(targetDetected(QNdefMessage,QNearFieldTarget*))); // Get notified when the tag gets out of range connect(nfcManager, SIGNAL(targetLost(QNearFieldTarget*)), this, SLOT(targetLost(QNearFieldTarget*))); connect(nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)), this, SLOT(targetDetected(QNearFieldTarget*))); nfcManager->startTargetDetection(); }
62 2011 Nokia Nokia NFC Development v. 1.1.6

Read NDEF Message


Detected a target? Read its message.
ndefmanager.cpp
void NdefManager::targetDetected(QNearFieldTarget *target) { qDebug() << "Target detected!"; const bool hasNdefMessage = target->hasNdefMessage(); if (hasNdefMessage) { connect(target, SIGNAL(ndefMessageRead(QNdefMessage)), this, SLOT(ndefMessageRead(QNdefMessage))); target->readNdefMessages(); } // Cache target to member variable for writing cachedTarget = target; }
63 2011 Nokia Nokia NFC Development v. 1.1.6

Target Lost
Set cached target to NULL
ndefmanager.cpp
void NdefManager::targetLost(QNearFieldTarget *target) { cachedTarget = NULL; // New target->deleteLater(); }

64

2011 Nokia Nokia NFC Development v. 1.1.6

Parse NDEF Message


Same code as before, different method
ndefmanager.cpp
void NdefManager::ndefMessageRead(const QNdefMessage &message) { // Go through all records in the message foreach (const QNdefRecord &record, message) { // Check type if (record.isRecordType<QNdefNfcUriRecord>()) { // Convert to the specialized URI record class QNdefNfcUriRecord uriRecord(record); // Emit a signal with the URI emit nfcReadTagUri(uriRecord.uri()); } } }
65 2011 Nokia Nokia NFC Development v. 1.1.6

Write URI Ndef Message


ndefmanager.cpp
void NdefManager::nfcWriteTag(const QString &nfcTagText) { // The device currently has a target in reach if (cachedTarget) { // Convert text to a URI, adding missing http:// if necessary QUrl convertedUrl = QUrl::fromUserInput(nfcTagText); // Check if it is a valid URL if (convertedUrl.isValid() && nfcTagText.contains('.')) { QNdefMessage message; // Create a URI NDEF record QNdefNfcUriRecord uriRecord; uriRecord.setUri(convertedUrl); message.append(uriRecord); qDebug() << "Writing URI ..."; // Write NDEF message to the tag cachedTarget->writeNdefMessages(QList<QNdefMessage>() << message); } else { qDebug() << "No valid URI"; } } else { qDebug() << "No cached target available"; } }
2011 Nokia Nokia NFC Development v. 1.1.6 August 16, 2011 Andreas Jakl

66

Extend UI with Write Button


Day.qml, between lines 122 / 123 (below MouseArea with id: mouse)
Image { id: writeButton source: "NfcFlag.png" rotation: -8 // Note image itself is rotated anchors { bottom: parent.bottom; right:parent.right } MouseArea { anchors.fill: parent onClicked: ndefManager.nfcWriteTag(myText.text) } }

NfcFlag.png
67 2011 Nokia Nokia NFC Development v. 1.1.6

<project dir>\qml\

Test!

https://projects.developer.nokia.com/nfccorkboards

Touch a tag, at the same time press the NFC flag of a note
Writes the note text to the tag Remember to enter a valid URI!
The extended solution on Nokia Developer Projects additionally handles text tags and potential errors.

68

2011 Nokia Nokia NFC Development v. 1.1.6

https://projects.developer.nokia.com/nfccorkboards

NFC Corkboards

Task Adding autostart feature

69

2011 Nokia Nokia NFC Development v. 1.1.6

Auto start feature


Create an xml file with the format given below ( for Symbian^3 )
<?xml version="1.0" encoding="UTF-8"?> <SFW version="1.1"> <service> <name>%APPNAME%</name> <ipcaddress>%APPNAME%</ipcaddress> <description>NFC NDEF message handler for %APPNAME%</description> <interface> <name>com.nokia.qtmobility.nfc.NdefMessageHandler</name> <version>1.0</version> <description>NFC NDEF message handler for %APPNAME%</description> <capabilities></capabilities> <customproperty key="datatype">%DATATYPE%</customproperty> </interface> </service> </SFW>
70 2011 Nokia Nokia NFC Development v. 1.1.6

Auto start feature


Recommended to name the xml file after the application package name XML file needs to be installed in the correct location. The following needs to be added into the .pro file
symbian { ndefhandler.sources = %APPNAME%.xml ndefhandler.path = /private/2002AC7F/import/ DEPLOYMENT += ndefhandler }

71

2011 Nokia Nokia NFC Development v. 1.1.6

Auto start feature


Make sure that the application calls registerNdefMessageHandler()
ndefmanager.cpp
NdefManager::NdefManager(QObject *parent) : QObject(parent) { // Get notified when the tag gets out of range connect(nfcManager, SIGNAL(targetLost(QNearFieldTarget*)), this, SLOT(targetLost(QNearFieldTarget*))); connect(nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)), this, SLOT(targetDetected(QNearFieldTarget*))); // Add this line below nfcManager->registerNdefMessageHandler(this, SLOT(targetMessageDetected(QNdefMessage,QNearFieldTarget*))); nfcManager->startTargetDetection(); }
72 2011 Nokia Nokia NFC Development v. 1.1.6

Auto start feature


Remember to add the targetMessageDetected() in the header/cpp files
ndefmanager.h
private slots: void targetMessageDetected(const QNdefMessage &message, QNearFieldTarget *target );

ndefmanager.cpp
void NdefManager::targetMessageDetected(const QNdefMessage &message, QNearFieldTarget *target) { qDebug() << "Target detected!"; ndefMessageRead(message); }
73 2011 Nokia Nokia NFC Development v. 1.1.6

https://projects.developer.nokia.com/nfcchat

NFC Chat

Tasks Develop an NFC chat from scratch NFC Peer to Peer mode LLCP Protocol (server & client sockets) Qt Quick UI

74

2011 Nokia Nokia NFC Development v. 1.1.6

App Overview

main.cpp
Application startup Loads and shows main.qml

main.qml
UI definition Defines data model and view

nfcpeertopeer.cpp/.h
Target discovery NFC Peer to peer sockets (client & server)

75

2011 Nokia Nokia NFC Development v. 1.1.6

New Project (SDK 1.1.2)


Qt Quick Application
Name: NfcChat Targets: only Qt 4.7.3 w/ QtM 1.2 (uncheck Qt 4.7.3 for Desktop)

Accept defaults for the rest


76 2011 Nokia Nokia NFC Development v. 1.1.6

New Project (SDK 1.1.3)


Qt Quick Application
Name: NfcChat Application Type: Qt Quick Application Components for Symbian Targets: only Qt 4.7.4 for Symbian Belle Accept defaults for the rest
77 2011 Nokia Nokia NFC Development v. 1.1.6

Add Connectivity
Edit the Qt project file (nfcchat.pro)
Uncomment & add mobility component: connectivity
CONFIG += mobility MOBILITY += connectivity

Add LocalServices Capability


symbian:TARGET.CAPABILITY += NetworkServices LocalServices
Allows Internet access Allows NFC

78

2011 Nokia Nokia NFC Development v. 1.1.6

UI Design
Delete existing main.qml and MainPage.qml

Add a new QML page main.qml


create the followings: Button (Image + mousearea) set id as sendButton

TextEdit set id as sendTextEdit


List View set id as messageView List Model set id as messageModel

79

2011 Nokia Nokia NFC Development v. 1.1.6

Solution: (main.qml)
import QtQuick 1.0 Rectangle { id: rectangle1 width: 360 height: 360 Image { id: sendButton x: 291 anchors.right: parent.right anchors.rightMargin: 0 anchors.top: parent.top anchors.topMargin: 0 source: "NfcButton.png" MouseArea { id: mouse_area1 anchors.fill: parent }} // continue next page }
80 2011 Nokia Nokia NFC Development v. 1.1.6

Solution: (main.qml)
TextEdit { id: sendTextEdit width: 80 height: 20 text: "Hello NFC" anchors.left: parent.left anchors.leftMargin: 0 anchors.top: parent.top anchors.topMargin: 0 font.pixelSize: 10 } ListModel { id:messageModel } // continue next page
81 2011 Nokia Nokia NFC Development v. 1.1.6

Solution: (main.qml)
ListView { id: messageView model: messageModel delegate: Text {text: chatMessage } anchors.right: parent.right anchors.rightMargin: 0 anchors.left: parent.left anchors.leftMargin: 0 anchors.bottom: parent.bottom anchors.bottomMargin: 0 anchors.top: sendButton.bottom anchors.topMargin: 0

}
82 2011 Nokia Nokia NFC Development v. 1.1.6

NfcPeerToPeer
Go to the Edit view New C++ class
Right-click the project
Add New ...

C++ Class
Class name: NfcPeerToPeer Base class: QObject
86 2011 Nokia Nokia NFC Development v. 1.1.6

Include
Headers, define member variable
nfcpeertopeer.h
#include <qnearfieldmanager.h> #include <qllcpserver.h> #include <qllcpsocket.h> QTM_USE_NAMESPACE // Use Qt Mobility namespace

[...] private: QLatin1String nfcUri; QNearFieldManager *nfcManager; QLlcpServer *nfcServer; QLlcpSocket *nfcClientSocket; QLlcpSocket *nfcServerSocket;
87 2011 Nokia Nokia NFC Development v. 1.1.6

Search for Targets


Save own unique service Uri and start target detection
nfcpeertopeer.cpp
NfcPeerToPeer::NfcPeerToPeer(QObject *parent) : QObject(parent), nfcUri("urn:nfc:sn:com.nokia.nfcchat") { nfcManager = new QNearFieldManager(this); connect(nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)), this, SLOT(targetDetected(QNearFieldTarget*))); connect(nfcManager, SIGNAL(targetLost(QNearFieldTarget*)), this, SLOT(targetLost(QNearFieldTarget*))); // Only detect other NFC devices. Leave the phone to handle NFC tags. nfcManager->startTargetDetection(QNearFieldTarget::NfcForumDevice);

}
88 2011 Nokia Nokia NFC Development v. 1.1.6

Signals & Slots


Handle targets
nfcpeertopeer.h
private slots: void targetDetected(QNearFieldTarget *target); void targetLost(QNearFieldTarget *target);

Emit chat messages to the UI


nfcpeertopeer.h
signals: void chatMessage(const QString& nfcClientMessage);

89

2011 Nokia Nokia NFC Development v. 1.1.6

React
New target: emit info message
nfcpeertopeer.cpp
void NfcPeerToPeer::targetDetected(QNearFieldTarget *target) { emit chatMessage("Target detected"); }

Target out of range: emit message & delayed object delete


nfcpeertopeer.cpp
void NfcPeerToPeer::targetLost(QNearFieldTarget *target) { target->deleteLater(); emit chatMessage("Target lost"); }
90 2011 Nokia Nokia NFC Development v. 1.1.6

Register C++ with QML


Make your C++ class available in QML
QML Name: NfcPeerToPeer

QML Library: NfcPeerToPeer 1.0


main.cpp
#include <QtDeclarative> #include "nfcpeertopeer.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); qmlRegisterType<NfcPeerToPeer>("NfcPeerToPeer", 1, 0, "NfcPeerToPeer"); [...] }
91 2011 Nokia Nokia NFC Development v. 1.1.6

NfcPeerToPeer in QML
Import module
main.qml
import NfcPeerToPeer 1.0

Update the list model when a NFC chat message arrives


main.qml
NfcPeerToPeer { id: nfcPeerToPeer onChatMessage: { messageModel.append( {"chatMessage": nfcClientMessage} ) } } ListModel { id: messageModel } ListView { model: messageModel delegate: Text { text: chatMessage } // [...] }
92 2011 Nokia Nokia NFC Development v. 1.1.6

Test!

Run the app on two phones

Note: NFC app cannot be deploy on C7 with Symbian Anna at this moment With SDK 1.1.3 .

Switch phones in the Run Settings

Touch both phones


Admire how they detect each other!

93

2011 Nokia Nokia NFC Development v. 1.1.6

Test in simulator!

94

2011 Nokia Nokia NFC Development v. 1.1.6

NFC LLCP Server Socket


Define slots for new server connections & sending text
nfcpeertopeer.h
public slots: void sendText(const QString& text); private slots: void handleNewConnection();

Listen for new server connections


nfcpeertopeer.cpp
NfcPeerToPeer::NfcPeerToPeer(QObject *parent) // [...] nfcServer = new QLlcpServer(this); connect(nfcServer, SIGNAL(newConnection()), this, SLOT(handleNewConnection())); nfcServer->listen(nfcUri); }
95 2011 Nokia Nokia NFC Development v. 1.1.6

Connections & Sending


Create a socket for a new server connection
nfcpeertopeer.cpp
void NfcPeerToPeer::handleNewConnection() { if (nfcServerSocket) { nfcServerSocket->deleteLater(); } nfcServerSocket = nfcServer->nextPendingConnection(); }

Slot to send chat messages over the server socket


nfcpeertopeer.cpp
void NfcPeerToPeer::sendText(const QString& text) { if (nfcServerSocket && nfcServerSocket->isOpen()) { nfcServerSocket->write(text.toUtf8()); emit chatMessage("Message sent"); } }

96

2011 Nokia Nokia NFC Development v. 1.1.6

Sending Chat Messages


Call the sendText() slot in MouseAreas onClicked handler
main.qml
onClicked: nfcPeerToPeer.sendText(sendTextEdit.text)

97

2011 Nokia Nokia NFC Development v. 1.1.6

NFC LLCP Client Socket


Define slot to read incoming text
nfcpeertopeer.h
private slots: void readText();

Create the client socket (to be connected to NFC targets)


nfcpeertopeer.cpp
NfcPeerToPeer::NfcPeerToPeer(QObject *parent) // [...] nfcClientSocket = new QLlcpSocket(this); connect(nfcClientSocket, SIGNAL(readyRead()), this, SLOT(readText())); }
98 2011 Nokia Nokia NFC Development v. 1.1.6

Connections & Reading


Connect the socket to a target in targetDetected()
nfcpeertopeer.cpp
nfcClientSocket->connectToService(target, nfcUri);

Read text from the socket and emit a signal


nfcpeertopeer.cpp
void NfcPeerToPeer::readText() { QByteArray rawData = nfcClientSocket->readAll(); QString data = QString::fromUtf8(rawData.constData(), rawData.size()); emit chatMessage(data); }

Cleanup in targetLost()
nfcpeertopeer.cpp
nfcClientSocket->disconnectFromService();

99

2011 Nokia Nokia NFC Development v. 1.1.6

Test! #2
Touch upper back of two phones
Note: NFC app cannot be deploy on C7 with Symbian Anna at this moment With SDK 1.1.3 . Click on the link to view details

https://projects.developer.nokia.com/nfcchat
The extended solution on Nokia Developer Projects includes cached text sending and error handling and is based on Qt Quick Components. Note: if installing the solution, uninstall your own app first to avoid a name conflict..

While touching, press the send button

100

2011 Nokia Nokia NFC Development v. 1.1.6

Nokia Store intake for Qt apps


27 Models Compatible with Qt 4.7 / QML Symbian^3: N8, E7, C7, C6-01, C7 Astound, E6, X7 and Oro S60 5th Edition: X6, C6-00, C5-03, N97, N97 Mini, 5800, 5530, 5250, 5235, 5233, 5230, 5228 (does not support Qt Quick Components) Nokia N9 Nokia N900 with PR 1.3 later

Compatible with Qt 4.6 (Qt mobility 1.0) All of the above S60 3rd Edition: E72, E71, E66, E63 and E52 Check here for the updated list: http://www.developer.nokia.com/Distribute/Packaging_and_signing.xhtml
101 2011 Nokia Nokia NFC Development v. 1.1.6

Where to find help?


http://www.developer.nokia.com/Community/Wiki/About_NFC Qt SDK
Help, examples

Discussion boards, wikis


Nokia Developer: http://developer.nokia.com/ Qt Developer Network: http://developer.qt.nokia.com/

e-Learning materials
http://qt.nokia.com/developer/learning/online/training/ http://qt.nokia.com/services-partners/qt-in-education/qt-in-education-course-material

Community
http://www.qtcentre.org/

102

Qt Books
(some recommendations)

Beginning Nokia Apps Development

Ray Rischpater, Daniel Zucker. Apress. Complete end-to-end story of developing for Symbian
and MeeGo with Qt (Quick) and HTML 5. Status: Qt 4.7, December 2010

Foundations of Qt Development

Johan Thelin. Apress.

More in-depth and technically oriented explanation of Qt different approach to many other books. Generic Qt, no mobile. Status: 2007

C++ GUI Programming with Qt 4 (2nd edition)

Jasmin Blanchette, Mark Summerfield. Prentice Hall.

Official book for generic Qt development (no mobile). Good for looking things up or for enhancing your knowledge, average for learning from scratch. Status: Qt 4.3, 2008
103

Nokia Certified Qt Developer


Official accreditation for individual developers
Confirms your development skills in Qt Become more attractive in the job market! Qt Essentials exam: 50 multiple choice questions, 60 minutes Qt Advanced exams: widgets and C++

104

Nokia Developer Champion & Qt Ambassador


Active community member?
Be even more involved, improve your network and get rewarded! Nokia Developer Champion http://www.developer.nokia.com/Community/Champions/ Qt Ambassador http://qt.nokia.com/qt-in-use/ambassadors/qtambassador/

105

Universities
Qt is a good way to teach software development
Instant results to motivate attendees Graphical tools make entry easier Flexible system, extensible with own libraries and still standard C++!

University support
Free Qt course materials under Creative Commons (PPT and OpenOffice)

http://qt.nokia.com/learning/education/course-materials Nokia Developer University support http://www.developer.nokia.com/Developer_Programs/Nokia_Developer_for_uni versities/


106

Your Feedback Counts!


Not happy with the way something works? Found a bug?
Submit your Qt bug report or suggestion to: http://bugreports.qt.nokia.com/ Unsure about what to include? The guide is here: http://developer.qt.nokia.com/wiki/ReportingBugsInQt Found a bug somewhere outside of Qt? Report it here: http://www.developer.nokia.com/Support/ Also go to the above URL to buy a commercial support ticket if needed!

107

Thank You.

108

2011 Nokia Nokia NFC Development v. 1.1.6

You might also like