Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

NFC Primer for Developers

by Retired on ‎09-28-2011 11:37 AM - edited on ‎10-28-2013 09:43 AM by BlackBerry Development Advisor (22,181 Views)

Introduction

This article is intended to act as a short and basic introduction to the world of NFC as it applies to BlackBerry® smartphones, such as the BlackBerry 9900 smartphone, and is aimed at developers who wish to take advantage of this exciting new technology. No prior knowledge of NFC is assumed but we do assume that the reader is familiar with Java® in some places.

 

The Authors

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

 

What is NFC?

"NFC" stands for "Near Field Communications" and from one perspective is simply a very short range radio communications technology. The range of NFC communications is typically no more than about 4cm whereas in contrast, the range of Bluetooth® is several metres, and Wi-Fi® potentially hundreds of metres. NFC is a key element in something referred to as "contactless card technology" which allows small devices such as smart cards to interact with other devices merely by being moved into sufficiently close proximity with the other device.

Looking at NFC systems more closely however, reveals that this radio capability sits within an overall system architecture which consists of a variety of components and which has the capability to make possible an interesting and exciting range of types of applications. We'll explore this in the next section.

 

What can you do with NFC and BlackBerry devices?

There are all manner of use cases which NFC could support. Here are some examples:

  • Smart Posters - embed small electronic "tags" containing data such as a URL in posters. An NFC enabled BlackBerry smartphone can read the data and act upon it just by holding the device close to the poster. The action taken when reading a tag will vary according to the type of data the tag contains and the nature of the application reading the tag but it could for example involve taking the user directly to a web site which contains more information about the advertised event/product (etc) on the BlackBerry Browser®, or automatically send an SMS requesting someone call back the user, and so on.
  • Ticketing - gain access to theatres, events, trains, buses etc
  • Payment - pay for goods or services using your NFC enabled BlackBerry smartphone very much as though it were a plastic credit card
  • Access - gain physical access to restricted areas or buildings. Gain logical access to the corporate network.
  • Data exchange - exchange data objects such as electronic business cards between BlackBerry smartphones just by tapping them together. Automatically configure smartphones by tapping them together. For example you may be able to configure your smartphone's Wi-Fi capability by tapping it against your Wi-Fi enabled router at home.
  • and much more.....

The variety of application types that are possible is wide but on closer inspection it turns out that there basically are two classes of NFC Devices supporting these use-cases:

  • An NFC-enabled device like a Point of Sale terminal or an NFC enabled phone (such as your BlackBerry smartphone). These are devices that are generally self powered and capable of transmitting or receiving on the NFC antenna under their own power.
  • An NFC tag is typically a passive device (for example, integrated in a smart poster) that stores data that can be read by an NFC-enabled device (such as your BlackBerry smartphone). It is not capable of operating under its own power and depends on the presence of a radio field from an NFC-enabled device like a card reader to power it.

These two NFC Device types determine a set of permutations to which there corresponds three possible "modes of operation" in which NFC can be used:

  • Tag reading and writing - used with "smart posters" for example where an NFC-enabled device can read or write a passive NFC Tag
  • Peer-to-peer (P2P) - used to transfer data objects between NFC-enabled devices such as two NFC-enabled smartphones
  • Card emulation (CE) - as the name suggests, this is where the NFC-enabled device (your BlackBerry smartphone) and the software it contains act to emulate some kind of contactless card. It could for example emulate a credit card to support paying for items or a transportation system access card. Card emulation is specified as being able to take place even when the NFC-enabled device is powered down; just as though it was a Tag.

The words "Card" and "Tag" tend to be used interchangeably. Technically they are both the same; however, contactless cards used in ticketing and payment today include additional technology to store secure data whilst the word Tag is generally used to refer to a passive devices such as a Smart Poster Tag.

 

How do users work with NFC?

To engage in an NFC use case users will hover their smartphone near another device (another NFC capable smartphone, a "smart poster", a contactless card reader or some other kind of NFC enabled device such as a Wi-Fi router). It's just possible however that while not strictly necessary, they will grow accustomed to actually tapping their device against the other device. There's no need to touch the other device from a technical point of view, but this very pro-active gesture of tapping one device against another has a very reassuring and satisfying feel to it and it is likely that this will catch on.

 

What is the architecture of a BlackBerry NFC solution?

The following diagram shows a somewhat simplified schematic of the architecture of the NFC system within applicable BlackBerry smart phones:

 

archiNFC.jpg 

 

The key components depicted here are:

  • NFC Antenna - NFC radio communications requires an antenna in the NFC device. On a BlackBerry 9900 smartphone for example, the NFC antenna is embedded within the door covering the battery compartment.
  • NFC Controller - Consists of an NFC Hardware Controller Interface ("HCI") and an NFC modem. This component interfaces with the NFC Antenna and redirects the RF (Radio Frequency) communication to the currently selected SE (Secure Element) amonst other things. It's the key piece of hardware which gives your BlackBerry smartphone its NFC capabilities. The NFC modem is sometimes termed the "CLF" or Contactless Front End. It's responsible for communication via radio with an external NFC reader.
  • Secure Element (SE) - this is a component which is also used in smart cards. It consists of hardware and a smart card operating system and is capable of running small applications known as "applets". The SE provides a secure, tamper proof environment for running applets. Full applications on the BlackBerry smartphone can interact with such applets using one of the BlackBerry NFC APIs (more on this later). Applets can also interact with "the outside world" i.e. components such as NFC reader terminals (e.g. point of sale terminals) using one of the key NFC communications protocols plus  a suitable application-layer protocol. A BlackBerry smartphone such as the BlackBerry 9900 smartphone supports two distinct SEs; the first is embedded within the device itself and often termed the "eSE" (for Embedded SE); the second resides within the UICC or as it used to be known, the SIM card. Only one of the two SEs may be active at a time.
  • NFC Stack - This is a software stack which consists of a series of APIs which BlackBerry applications and MIDlets can make use of. These APIs include implementations of JSR 177 and a series of proprietory RIM APIs which give similar capabilities to those found in JSR 257.
  • BlackBerry Applications - these are applications which provide whatever required functionality is desired and make use of the NFC APIs for NFC use cases. Currently BlackBerry NFC applications must be written in Java.

 

There are other acronyms shown on the diagram above and a few that have been deliberately excluded. Let's not worry about them for now. You'll find most of them defined in the glossary at the end of this article.

 

ISO Standards

A number of ISO standards apply to the world of NFC. Whether you need to know anything about them, a little about them or a great deal will depend very much on what kind of application you are involved with developing and what your role is. It's worth having an awareness that these standards apply at the very least though. Two key ISO standards to be aware of are ISO 7816 and ISO 14443. Both define various layers of a stack from the physical layer upwards and therefore break down into a number of parts. ISO 7816 is concerned with "electronic identification cards with contacts" and ISO 14443 is concerned with contactless cards. As you can see from the following diagram, ISO 7816 part 4 defines the APDUs used to communicate with a card or in this case an applet running in an SE via the "with contacts interface" and ISO 14443 defines the interface from the contactless side to external entities such as NFC point of sale readers.

 

ISO_standards.jpg

 

How do I code my NFC application?

It depends on what you want to do. What you want to do will correspond to one of the three modes of operation mentioned above. There are also some differences between BlackBerry applications and J2ME MIDlets. We won't get into too much detail in this article but we will be following up with other articles which explore typical use cases and the associated APIs in more depth soon.

 

Working with smart posters / tags

Data stored in NFC tags must be structured according to something known as NDEF. NDEF stands for "NFC Data Exchange Format" and it defines message types, record types and encoding rules for various types of NFC tag content, such as telephone numbers, text, or URLs. You need to have some familiarity with NDEF to be able to work with the data structure. Ideally you should work with the appropriate NDEF specification, available from http://www.nfc-forum.org/specs/spec_list/ .

 

The BlackBerry Java APIs include a package called net.rim.device.api.io.nfc.ndef and this contains most of the classes and interfaces you will need. To have your application receive particular types of NFC tags when they enter the device's NFC field, you must implement and register an instance of the NDEFMessageListener interface. To register your application for a given type of NDEF message, you must call the addNDEFMessageListener method of the net.rim.device.api.io.nfc.readerwriter.ReaderWriterManager class. You can and usually should indicate that your application should be automatically started if its not running, when an NDEF message of the specified type is encountered. You do this via the final parameter to the addNDEFMessageListener method whose full signature looks like this:

 

public void addNDEFMessageListener(NDEFMessageListener listener,

                                                                      int typeNameFormat

                                                                       String recortType,

                                                                       boolean autoStart)

                                                         throws NFCException

 

     Registers a listener to receive notifications when an NDEF message is read by the BlackBerry® device

 

     Parameters:

           listener - The NDEFMessageListener object

           typeNameformat - An NDEF type name format.

           recordType - An NDEF record types.

          autoStart -Indicates whether the application should be started if not running.

     Throws:

            NFCException - When the listener cannot be added.

            SecurityException - If an IT policy disallows NFC or NFC read/write.

            ControlledAccessException - If read/write is disabled by application permissions.

      Since:

            BlackBerry API 7.0.0

 

 

Note however that while your NDEFMessageListener application will be automatically started if necessary when autoStart was set to true when registering, it must re-establish itself as a listener (by calling addNDEFMessageListener) again on starting otherwise even though it has been started, it will not receive a callback to the interface.

 

When your application receives a callback to the NDEFMessageListener's onNDEFMessageDetected method it will receive an NDEFMessage object as a parameter. You'll need to parse this message per the NDEF specifications and then act upon the message as you require.

Working with NDEF tags does not require use of either of the SEs by the way and is the simplest of the NFC modes to work with.

 

Card emulation

This is the most challenging of the three NFC modes to work with. Typically, card emulation is achieved by installing an applet in one of the two SEs. The applet will, amongst other things, emulate a given type of smart card. So for example, if your aim is to implement support for a given physical access system then you will need to establish details of the protocol used to "talk" between a physical access smart card and the readers attached to doors and their associated physical access control systems. You'll also need to establish whether or not the NFC system in your BlackBerry smartphone is compatible with the specific contactless communications protocols in use since there are many variations. We won't go into this in detail here but examples include ISO14443A, ISO14443B and ISO15693. Working directly with the supplier of the physical cards which you wish to emulate may be the only way to acquire this information.

Once you have an applet in an SE however, as an application developer (as opposed to *applet* developer) you will be concerned with a number of issues. Again, we'll be publishing articles which look at these issues in more detail, but to get you started, here are some key examples:

 

1. Talking to the applet on an SE

This breaks down into two problems in fact; how to select the SE which contains the applet you wish to talk to and then how to talk to that applet.

The first issue is dealt with using RIM APIs such as the SecureElementManager and SecureElement classes, both of which can be found in the net.rim.device.api.io.nfc.se package. Selecting an SE is achieved using code such as the following fragment:

 

SecureElementManager sem = SecureElementManager.getInstance();
SecureElement se = null;
try 
{ se = sem.getSecureElement(SecureElement.EMBEDDED); }
catch (NFCException e1)
{ // handle Exception }

 

Since only one SE may be active at a time, you also need to route particular protocols to your selected SE according to the various states the SE can be in. We won't go into detail on what all this means in this introductory article but this should give you the flavour of what is involved:

 

try 
{ // Route ISO14443A to the Secure Element for battery on mode se.setTechnologyTypes(SecureElement.BATTERY_ON_MODE, TechnologyType.ISO14443A);
}
catch (NFCException e)
{ // handle the Exception }

  

Talking to an applet on an SE involves the use of a protocol defined in specification ISO7816 part 4. This specification defines APDUs (Application Protocol Data Units) or message types which can be sent as requests to or received as responses from applets stored on a smart card. Since an SE is essentially a smart card, it applies here too. As a BlackBerry Java application developer, you use the JSR 177 APIs to establish a connection to an applet on the SE and then exchange request and response APDUs with it. The key package is javax.microedition.apdu which defines the APDU protocol handler for ISO7816-4 communication to a smart card device and includes the interface APDUConnection. Here's a simple example:

 

 // The JSR177 connection will use the APDUConnection object
 APDUConnection apduConn = null;
 // The connection string for the JSR177 connection
 String conStr = "apdu:0;target=41.5F.50.5F.44.5F.55.5F.41.70.71.01";
 // Define the command to send to the Smart Card applet
 byte[] command = { (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x00 };
 
 try 
{ // Open a logical channel to the application apduConn = (APDUConnection) Connector.open( conStr ); // Send an APDU and wait for a response byte[] ret = apduConn.exchangeAPDU( command ); // Close the logical channel connection apduConn.close(); }
catch( Exception e )
{ // handle the Exception }

  

2. Being informed of activity in an applet

An applet in an SE may function quite independently of any application on the BlackBerry smartphone. For example, exchanging messages via an adjacent external reader does not require an application's participation usually. The applet takes care of this on its own. But you may wish your application to be notified when certain events take place. The BlackBerry APIs include the TransactionListener interface in the net.rim.device.api.io.nfc.se package which you may implement and register for this purpose. Registration is achieved by calling the addTransactionListener method on a SecureElement object. An application which acts as a TransactionListener will receive call backs to its onTransactionDetected method when events take place within the SE or HCI but must be running to receive such call backs. It may be useful to implement a background application which auto-starts to act as a TransactionListener.

 

void onTransactionDetected (byte[][] aids)

 

     Invoked when an external reader completes a transaction with an application stored on a Secure Element.

 

     Parameters:

          aids - Array of Application IDs used in the last transaction between an external reader and a secure        
          element.

     Category:

          Signed: This element is only accessible by signed applications. If you intend to use this element, please
          visit http://www.blackberry.com/go/codesigning to obtain a set of code signing keys. Code signing is only
          required for appplications running on BlackBerry smartphones; development on BlackBerry Smartphone
          Simulators can occur without code signing.

     Since: 

          BlackBerry API 7.0.0

 

 3. Being informed of events in the NFC field

You may wish your application to be notified whenever something happens within the NFC radio field. For example, a reader or tag entering the field could be of interest to your application. To that end, the BlackBerry APIs include the net.rim.device.api.io.nfc.readerwriter.DetectionListener interface which you may implement and register using the ReaderWriterManager class. Should a relevant event occur, your application will receive a call back to its onTargetDetected method. It may then obtain a connection object over which to send APDUs or to allow interaction with a tag.

 

void onTargetDeteted(Target target)

 

     Invoked when a connection to an NFC target is detected. The connection to an NFC target is retrieved by the  
     following code: Connection.open(target.getUri(Target.NDEF_TAG)); Make sure that any
     communication with the Target occurs on the main event loop.  The BlackBerry® deice doses the    
     connection to the Target when the onTargetDetected method finishes.

 

     Parameters:

          target - An NFC target.

     Since:

          BlackBerry API 7.0.0

 

Peer to peer mode

Support for Peer-to-peer mode NFC was added to the BlackBerry Java APIs as at version 7.1 and is the subject of the following two knowledge base articles:

 

Peer to Peer Communication with SNEP

 

Peer to Peer Communication with LLCP

 

Code Signing

Your application will need to be signed in the usual way per any typical BlackBerry Java application. We have however introduced a couple of new signing keys, NFCR and RESE. You will need to sign your application with the NFCR key if you are using any of the classes or interfaces in the net.rim.device.api.io.nfc.se package with the UICC resident SE (SIM). Similarly you will need to sign with the RESE key if your application uses the net.rim.device.api.io.nfc.se package with the device embedded SE. Note that these signing keys are only available by application to RIM at this stage.

 

Summary

Hopefully this article has given you some insight into what NFC is about in general and the kinds of exciting things you can do with NFC and a suitable BlackBerry smartphone. The APIs are available today so download the latest BlackBerry JDK from

 

http://us.blackberry.com/developers/blackberry7/

 

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

 

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
  • 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
Users Online
Currently online: 4 members 696 guests
Recent signins:
Please welcome our newest community members: