Welcome to the Official BlackBerry® Support Community Forums. This is your resource to discuss support topics with your peers, and learn from each other. New to the forum? Please visit the ‘Getting Started’ link below.
inside custom component

Web and WebWorks Development

NFC - NDEF Tag Reading from WebWorks Applications

Started 12-07-2011 by
Modified 01-30-2012 by

Introduction

This article is part of a series intended to act as an introduction to the world of NFC as it applies to BlackBerry® smartphones such as the BlackBerry® Bold™ 9900 and is aimed at developers who wish to take advantage of this exciting new technology. Readers of this article should have some pre-existing knowledge of the fundamental architecture of NFC systems and be familiar with the BlackBerry® WebWorks™ SDK. Familiarity with Java® is required for those parts of the article which deal with the sample WebWorks extension that illustrates how to add NFC NDEF capabilities to a WebWorks application.


Importantly, unless you already have good knowledge of the subjects covered, it’s recommended that you read the articles in this series entitled: "NFC Primer for Developers" and “Reading and Writing NFC Smart Tags”. Links to these articles can be found at the end of this one.


This article will look specifically at an example WebWorks extension which allows WebWorks applications to read NFC Smart Posters.

 

The Authors

This article was co-authored by Martin Woolley and John Murray both of whom work in the RIM Developer Relations team. Both Martin and John specialise in NFC applications development (amongst other things).


About this article

The BlackBerry® 7.0 Java APIs provide BlackBerry Java developers with the ability to read and write NFC tags. However, what about BlackBerry WebWorks developers? Well, as this article and attached sample code will illustrate, WebWorks developers too can quite easily exploit NFC in their applications.

 

BlackBerry Web Works Extensions

The BlackBerry WebWorks SDK allows developers to create great looking and functionally rich BlackBerry applications for either: the BlackBerry smartphone range, the BlackBerry® PlayBook™ tablet or both!


Developers use HTML5, JavaScript® and CSS and can leverage a growing WebWorks API to incorporate native device functionality in their applications. The WebWorks API takes the form of a collection of JavaScript functions that provide functionality relating to a large range of areas. Occasionally however, a developer will find that there is no standard WebWorks API function which does what they want. The WebWorks SDK is extensible and developers can write their own extensions which add new APIs that their WebWorks application can exploit.

 

At the time of writing, the WebWorks SDK has no standard NFC capabilities. So the authors of this article have put together a WebWorks extension for the BlackBerry smartphone range and the source code is available in the WebWorks GitHub repository (details below). The extension allows WebWorks applications to register to receive NDEF smart poster messages. A simple WebWorks application which uses the extension is also in the repository.

Let’s explore what was involved in creating the extension and how it can be used from a simple WebWorks application.

 

The Sample WebWorks Application

When started, the sample WebWorks application automatically registers as an NDEF listener for NDEF messages relating to “smart posters”. It has a simple, one page user interface (as shown in Figure 1) that provides two buttons which can be used to unregister or re-register an interest in receiving NDEF messages. After registering, an NFC smart poster entering the NFC radio field of the BlackBerry smartphone will cause an alert containing the NDEF message in JSON format to be displayed as shown in Figure 2.


A “real” application would of course do something more interesting with the NDEF message. But we’ll leave such creativity to you, the BlackBerry WebWorks developer.

 

Figure 1 - WebWorks application user interface

Figure 1 - WebWorks application user interface

 

Figure 2 - An NDEF message is received by the WebWorks application

Figure 2 - An NDEF message is received by the WebWorks application

 

The sample application code resides in a single file, “index.html”. It includes the in-line JavaScript functions shown here:

 

function initLogging() {
	var ok = blackberry.nfc.ndef.init_logging();
	if (ok) {
	} else {
		alert("The was a problem initialising logging");
	}
}
function registerListener(record_type) {
	var ok = blackberry.nfc.ndef.register_ndef(ndefMessageReceived, onNdefError, record_type);
	if (ok) {
		alert("NDEFMessageListener registered OK for record type "+record_type);
	} else {
		alert("There was a problem registering a NDEFMessageListener for record type "+record_type)
	}
}
function removeListener(record_type) {
	var ok = blackberry.nfc.ndef.unregister_ndef(record_type);
	if (ok) {
		alert("NDEFMessageListener unregistered OK for record type "+record_type);
	} else {
		alert("The was a problem unregistering the NDEFMessageListener for record type "+record_type)
	}
}
// call back functions
function ndefMessageReceived(ndef_message) {
	alert("NDEF message:"+ndef_message);
}
function onNdefError(error_message) {
	alert("NDEF error:"+error_message);
}

  

 

The JavaScript in the index.html page reveals the various API functions exposed or used by the WebWorks extension. These are:

 

Functions

Descriptions

 

blackberry.nfc.ndef.init_logging()

 

The extension classes write log messages to the BlackBerry event log if logging has been switched on.

 

Calling this API function achieves this. You can then extract the log file from your device using the javaloader tool:

 

javaloader -u eventlog > eventlog.txt

 

or you may view it on device by keying “ALT+LGLG”.

 

Notice that messages are logged at the Information level.

 

 

blackberry.nfc.ndef.register_ndef(

    <callback function>,

    <callback error function>,

    <NDEF record type>

)

 

By calling the “register_ndef” function, you register your application’s interest in a specific NDEF record type. The sample extension only supports smart posters (record type=’Sp’) at this stage. You must also supply the names of functions which will

a) receive NDEF messages from the extension via a call back and

b) receive any error messages which may need to be reported by the extension

 

 

blackberry.nfc.ndef.unregister_ndef(

     <NDEF record type>

)

 

By calling unregister_ndef you unregister your application as a listener for the given type.

 

 

ndefMessageReceived(ndef_message)

 

To be able to receive NDEF messages of a given type when detected, you must implement a JavaScript function which can accept a single parameter as shown. You must supply the name of this function to your invocation of the blackberry.nfc.ndef.register_ndef function. In our example, the name used is ndefMessageReceived but you can choose your own function name. You may also register a different function for each registered NDEF record type or use the same function for all types, the choice is yours.

 

On detecting an NDEF message of the registered type, the extension will make a call back to the named JavaScript function, passing the NDEF message as a string variable.

 

The string is a JSON formatted representation of the NDEF message which your application may then process according to its requirements.

 

onNdefError(error_message)

Errors which occur whilst processing an NDEF message will be reported via a call back to the call back error function that was specified when registering for the NDEF message type. Here we used the name onNdefError but you can choose your own name.

 

The “index.html” page uses an “onLoad” handler to initialise itself:

 

<body onLoad="initLogging();registerListener('Sp');">

 

As you can see, when the WebWorks application is first loaded and its single screen is displayed, it immediately initialises the logging system and calls the registerListener() method so that the application is ready to receive messages relating to NDEF smart posters.

Note that clicking the “Register NDEF Listener” button at this point will generate an error since the application is already registered.

Now that we’ve reviewed the content of the sample WebWorks application, let’s examine the extension code which provides NFC NDEF capabilities to the Web Works application.

 

The WebWorks NFC NDEF Extension

Overview

You should already be familiar with the concept and practice of implementing WebWorks extensions. If you’re not, it is suggested that you review the following documentation from the BlackBerry HTML5 and WebWorks microsite:

https://bdsc.webapps.blackberry.com/html5/documentation/ww_developing/using_javascript_extensions_18...

 

This sample WebWorks application has been developed against BlackBerry WebWorks Smartphone SDK version 2.2.0.15 which was the most recent version at the time of the writing of this article.


The “src” directory of the extension project (see Figure 3) contains a number of Java classes contained within a package called “widgetpackage”. It also includes an XML file called “library.xml” which defines the feature ID to be used from within JavaScript as the prefix to API methods exposed by the extension and the Java class which implements the “WidgetExtension” interface.


We’ll describe each of the classes and interfaces next.

For those people in a hurry however, those classes whose names begin with “Function” implement the three API functions:

  •          WidgetNdefMessageListener is where NDEF messages are received from the device NFC stack;

  •          NdefMessageParser parses the data received and turns it into a JSON string;

  •          NdefJavaScriptBridge passes that JSON string to your Web Works application by calling theJavaScript callback function you specified when registering for this type of NDEF message.

Simple! J

 

extension_classes.jpg 

Figure 3 - The NfcExtension project source

 

The Extension Classes and Interfaces

Here is a brief description of the objects as shown in the project in Figure 3

 

Item

Description

 

Constants

 

This contains the definitions of various constant String variables.

 

 

FunctionInitLogging

 

This is a sub-class of ScriptableFunction that implements the “init_logging” function and switches on the logging to the event log.

 

It achieves this by making the following call:

 

Utilities.initLogging(log_id, app_name);

 

Note that you can supply your own “app_name” value as an argument when you call this JavaScript.

 

If you do not, a default value of “NfcExtension” is used and this becomes the application name you will see in the BlackBerry event log viewer.

 

 

FunctionRegisterNdefListener

 

This is a sub-class of ScriptableFunction that implements the “register_ndef” function. It  accepts as parameters, a mandatory JavaScript function which will be called to deliver ndef messages, a second mandatory JavaScript function which is used for reporting errors and optionally, a third parameter which may specify an NDEF record type. In the absence of the third, optional parameter, a default value of “Sp” (the official designation of a Smart Poster from the NFC Forum) is applied. Note though, that for the moment, the sample code supports only “Sp” (smart poster).

 

This means that you should not use other record type values unless you are also prepared to enhance the NdefMessageParser so that it supports your type.

 

Execution of the invoke() method proceeds by registering the specified NDEF record type and associated call back functions with the FunctionRegistry and then using the NFC ReaderWriterManager class to register the WidgetNdefMessageListener singleton object as an NDEF message listener for the given record type. This registration call is handled as shown:

 

ReaderWriterManager manager = ReaderWriterManager.getInstance();

 

manager.addNDEFMessageListener(listener,

            NDEFRecord.TNF_WELL_KNOWN, record_type, true);

 

Notice carefully that a final parameter value of true is specified.

 

This indicates that if a smart poster tag is encountered when our WebWorks application is not running the application it will be automatically launched for us.

 

Under these circumstances the WebWorks application must register as an NDEF listener very soon after being launched (within 15 seconds is a good rule of thumb) in order to receive the call back containing the NDEF message itself.

 

This is achieved through making a call to registerListener('Sp') in our index.html page’s onLoad handler. The net result of all this is that, irrespective of whether our WebWorks application is running or not, it will receive the NDEF message and have the opportunity to process it; provided it has registered at some point to be an NDEF message listener for smart posters at some point after the device was powered on.

 

FunctionRegistry

Maintains a register of NDEF record types and associated call back functions.

 

FunctionUnregisterNdefListener

 

This is a sub-class of ScriptableFunction which implements the “unregister_ndef” function.

 

It too can accept a record type as a parameter; though, once again, please do note that the sample extension supports only smart poster messages at this time.

 

The invoke method proceeds by calling removeNDEFMessageListener on a ReaderWriterManager object as shown:

 

ReaderWriterManager manager = ReaderWriterManager.getInstance();

 

manager.removeNDEFMessageListener(NDEFRecord.TNF_WELL_KNOWN, record_type);

 

 

NdefJavaScriptBridge

 

This class is a singleton whose purpose is to pass a parsed NDEF message in JSON format back up to the JavaScript in our WebWorks application where it can be acted upon.

 

Its method “useNDEFMessage” is called by the NDEFMessageParser and receives the parsed NDEF message as a JSON string.

 

It then communicates the JSON string to the WebWorks application by invoking the ScriptableFunction object obtained from the FunctionRegistry singleton for the relevant NDEF record type.

 

Similarly, its reportError function looks up the error reporting call back function for a specified record type and calls it to report errors up to the web application layer.

 

NdefMessageParser

 

This is a simple parser which extracts a smart poster NDEF message from the message received from the NFC interface.

 

Note that it only supports smart poster (“Sp”) record types. It implements the Runnable interface so that it can run in a background thread and not block the NFC interface during a potentially lengthy parsing operation.

 

You may recognise some of this code from the article entitled “Reading and Writing NFC Smart Tags” here: http://supportforums.blackberry.com/t5/Java-Development/Reading-and-Writing-NFC-Smart-Tags/ta-p/1379...

 

NfcExtension

This implements the WidgetExtension interface.

 

All WebWorks extensions must include a class which implements this interface.

 

It defines a feature ID of “blackberry.nfc.ndef” and links this to the ScriptableNdef class which maps the individual API function names of “register_ndef”, “unregister_ndef” and “init_logging” to the classes which implement the appropriate logic.

 

 

ScriptableNdef

 

Our WebWorks extension must include a class which extends Scriptable and maps the individual API function names of “register_ndef”, “unregister_ndef” and “init_logging” to the classes which implement their logic.

 

 

Utilities

 

A simple “utility” class which contains various static methods including those concerned with logging to the event log.

 

 

WidgetNdefMessageListener

 

This implements the NDEFMessageListener interface. It is here that NDEF messages are initially delivered by the NFC sub-system.

 

On receipt of a call back to its onNDEFMessageDetected() method, it invokes the parseAndDeliver() method of the NdefMessageParser, resulting in the message being parsed and converted into a JSON string which is then delivered via the NdefJavaScriptBridge to our JavaScript code.

 

NdefMessageParser.getInstance(message).parseAndDeliver(message);

 

 

 

The JSON Message

The screen shot (see Figure 2) of the sample WebWorks application as it receives an NDEF message, displays a typical message in JSON format as used by the extension’s parser.

 

{
  “id” : “”,
  “type”:”Sp”,
  “type_name_format”:1,
  “url”:”http://www.appstore.blackberry.com/webstore/”,
  “text”:”More than apps. Super Apps. Only at BlackBerry App World.”
}

 

You should compare this with the content of an NDEF message as read and parsed as part of the “Reading and Writing NFC Smart Tags” article.

 

Future Evolution of the Extension

The code for the WebWorks extension described in this article is available from our GitHub repository. We’d love to see contributions from the community which result in the extension becoming more fully functional and useful. The initial version presented here only supports smart posters and does not support updating tags. Nor does it support other aspects of NFC. There’s a lot we could do together.


As far as NDEF tags are concerned, we believe there to be no reason to design a JSON structure to represent NDEF messages. That work has already been done by the NFC Forum. What we need from our Web Works extension is a way to deliver that same structure in a JSON format. Just our $0.02. What do you think?

 

Summary

This article should have demonstrated how easy it is to exploit NFC from a WebWorks application. Here at RIM, we intend to make it easier for you though and you should watch out for the new NDEF Helper classes in version 7.1 of the APIs which are coming soon.

The place to go for more information on the BlackBerry WebWorks SDK is here:

https://bdsc.webapps.blackberry.com/html5/ 

 

BlackBerry Java APIs are documented here if you'd like to browse further: http://www.blackberry.com/developers/docs/7.0.0api/

 

Source code for the WebWorks NFC extension described in this article is in the following GitHub repository:

https://github.com/blackberry/WebWorks-Community-APIs

 

And finally, the sample application can be found embedded in the page here:

https://github.com/blackberry/WebWorks-Community-APIs/tree/master/Smartphone/NFC

 

Other BlackBerry Developer NFC Articles

 

See the NFC Article Index for the list of other articles in this series

 

 

 

Glossary of NFC Terms

  • APDU - Application Protocol Data Unit. A message type which forms part of a protocol and which may be exchanged between peers as either a request or a response message. Applications on a BlackBerry smartphone may communicate with applets in an SE using the ISO7816-4 APDUs for example.
  • CLF - Contactless Front-end. Part of the NFC Controller. Communicates via RF with an NFC reader.
  • HCI - Hardware Controller Interface. Amongst other things, this component of the NFC system architecture redirects radio communication to appropriate SE.
  • ISO7816-4 - the specification which defines the protocol which allows applications to communicate with applets installed in an SE or smart card.
  • NDEF - NFC Data Exchange Format
  • NFC - Near Field Communications
  • PCD – Proximity Coupling Device (also known as “card reader”)
  • PICC – Proximity Integrated Circuit Card
  • SE - Secure Element. A hardware component which can host and act as an execution environment for small software applications known, in this context, as "applets".
  • SIM - Subscriber Identity Module. In 2G modules this used to be synonymous with the SIM *card* i.e. the small smart card inserted in the handset. In 3G networks, the SIM is a software module installed on the UICC.
  • SWP - Single Wire Protocol.
  • UICC - Universal Integrated Circuit Card - the smart card used in mobile terminals in GSM® and UMTS® networks

 

 

Contributors