This article is sponsored by the Java Community Process.
The Web Within an Arm's Reach

Near-Field Communication with JSR 257

by Frank Sommers
October 5, 2005

Summary
The Java Contactless Communication API (JSR 257) enables mobile devices to communicate via short-range wireless means, such as RFID, infrared light, or even Bluetooth, and presents such devices via a simple, homogeneous interface to Java applications. This article explains the role of the Java Contactless Communication API in the emerging field of near-field communications, and provides an example of reading data from any contactless target, including an RFID tag.

In his keynote address at the 2005 MIT Emerging Media Conference, Sun co-founder-cum-venture capitalist Bill Joy recounted his theory of the Six Webs[1]. Conceived over ten years ago, Joy's idea encourages us to look beyond Web browsers when thinking about the Web's future. In Joy's classification, the Web you are using to read this article is only one of six manifestations of the Web. That "near Web" requires you to sit at a computer, fire up a Web browser or email program, and then let those desktop applications bring content from the Web to your computer.

The near-Web is already fairly well-understood, and its key players have marked their territories in recent years. The remaining five Webs, however, hold enormous opportunities in Joy's opinion, having already started life in embryonic form. Those opportunities lie in the following areas:

  • The Far Web: This is the part of the Web that stores content you access from entertainment devices, such as large-screen TVs via remote control. Precursors of the Far Web are interactive video games; in the future, think personalized, streaming content coming to a wide-screen in your living room.

  • The Here Web: Instead of forcing you to seek out a network-connected computer to bring information near you, the Here Web allows you to connect anywhere, any time. Mushrooming wireless hotspots, in-flight Internet access, and Web access from your cell phone are just early signs of this Web's potentials.

  • The Weird Web: While the traditional, "near Web" is mostly about communication via HTML links and mouse clicks, the weird Web allows content access via voice instead of keyboard and mouse. You can ask this Web to fetch some content for you, and it will allow you to contact someone instantly. Voice-over-IP is one example of the Weird Web, but more intelligent applications will emerge on top of VOIP. Think Skype on steroids.

  • The B2B Web: You can already glimpse this Web in embryonic form in the burgeoning business-to-business Web exchanges. Except that you can't really "glimpse" these exchanges, because they have no interface to the consumer. They're sort of the anti-Amazon.com. Instead of pleasing consumers, they are designed to facilitate pure business-to-business interactions that, in the future, will involve less and less human intervention.

  • The D2D Web: While the B2B Web allows business systems to communicate, the D2D Web provides a way for devices to interact. That assumes that devices are embedded into everything from the wall of your room to the walls of your arteries. These devices will communicate through wireless means, and form intelligent networks to support activities such as controlling a building's temperature or monitoring your blood pressure. Sensor networks and Radio-Frequency Identification Systems (RFID) are just a few early examples of this Web.

  • Go Contactless

    The Java Contactless Communication API, developed through the JCP as JSR 257, addresses the communication needs of a significant subset of the D2D Web: Devices that reside within about an arm's reach of where you are[2]. If you look around, you can probably observe devices that already have some form of built-in capability to communicate with other devices within that short radius. For instance, your notebook computer may have the ability to communicate with your cell phone or PDA via Bluetooth. Or your PDA may be able to sync up with your desktop computer using infrared light.

    These devices employ contactless communication: communication that requires no wires, and is limited in range from a few inches to a few feet. Also termed near-field communication, contactless communication technologies include radio-frequency identification (RFID), optical barcode readers, and even infrared communication.

    Contactless communication capability is built into an increasing variety of physical objects, such as credit cards, PDAs, mobile phones, airport kiosks, and even packaging materials, facilitating peer-to-peer interaction between these objects and a remote reader. The city of Taipei's public transportation system, for instance, started to use near-field communication technology to facilitate the purchase of bus and train tickets from mobile phones equipped with near-field communication transmitters. The fare is billed to the customer's mobile phone account. More recently, some credit cards include near-field communication capabilities to offer contactless monetary transactions, eliminating the need to swipe a credit card at the point of purchase.

    A special form of contactless communication, RFID tags attached to physical objects respond to radio frequencies emitted from a reader device, and transmit globally universal manufacturer and product codes[3]. Combined with sensors, such tags may also transmit detailed product- and time-specific information, such as a product's current temperature and location. RFID tags are designed for high-volume, inexpensive manufacture, and thus promise ubiquitous near-field communication access to information about all sorts of physical objects that currently have no place on the Web. For example, while waiting in line to purchase a movie ticket, an RFID tag embedded in the movie poster could allow your cell phone to automatically connect to a URL recorded in the tag, and download and play a movie preview.

    Bootstrapping the D2D Web

    While wire-based communication is often initiated at the moment a cable connects two or more devices, wireless communication technologies rely on bootstrapping mechanisms specific to each technology. Having to deal with differing bootstrapping technologies presents a challenge to developers wanting to harness that special corner of the D2D Web. For instance, establishing a Bluetooth connection between two Bluetooth-enabled devices requires a priori "pairing" of the devices. That requirement diminishes usability, since the user has to first arrange the communication between the devices before software could take advantage of that connection. A similar situation exists with other wireless and near-field communication technologies, as anyone regularly visiting wireless hotspots could confirm.

    A more desirable situation would hide that communication bootstrapping from the user, and even from applications built to exploit contactless communication. A key value of the Java Contactless Communication API is that it provides that bootstrapping abstraction to Java applications. Applications on a JSR 257-enabled device can register with a DiscoveryManager to receive notifications when other near-field communication-enabled devices come into proximity. Based on the type of event, an application can query that newly discovered device and retrieve data from it.

    Since devices taking advantage of contactless communication often have but scarce memory and processing resources, applications may also register with a special PushRegistry, and request that they be "awakened" when certain discovery events are received. That alleviates the need for applications interested in near-field communication events to continuously stay resident in memory.

    For those familiar with Jini and RMI, the Contactless Communication API may sound much like a pared down version of those technologies. The Jini API even has a DiscoveryManager class to facilitate service discovery[4]. In addition, Jini's initial vision depicted communication networks formed spontaneously by Jini-enabled devices. The crucial difference between Jini and the Contactless Communication API is that Jini's discovery protocol centers around services. Indeed, services in a Jini network are defined via Java service interfaces, and the Jini discovery protocols locate and initiate communication with services based on the interfaces those service implement.

    The devices the Contactless Communication API aims to discover and interact with cannot be called services in the Jini sense. Instead, JSR 257's focus is the discovery and retrieval of tiny pieces of data from devices, which is often all such devices can offer. Once the Contactless Communication API retrieves and processes those small data items, it may typically hand that data to other applications via events, perhaps even triggering such applications to load into memory as a result of those events. Higher-level applications can interpret that data in application-specific ways, and take actions, if needed.

    Some of those actions may involve further communication with the newly discovered device, using a higher-level communication protocol, such as Bluetooth, for example. The Contactless Communication API helps bootstrap that higher-level communication by transferring just enough data from one device to another to seed the higher-level protocol. Conceptually, that bootstrapping is similar to how the Dynamic Host Configuration Protocol (DHCP) helps bootstrap higher-level TCP/IP-based communication between hosts.

    Communicating with RFID tags

    While the Java Contactless Communication API can work on any mobile device, the API's main focus in the first release is RFID tags and barcode information. That focus is explained by the JSR 257 expert group's belief that RFID tags will find uses even beyond their current niche in manufacturing and inventory control. "While RFID is still relatively new, we believe it will find broad uses beyond what we see now," says Jaana Majakangas, a Nokia engineer, and specification lead for JSR 257. One area Majakangas forsees RFID use is in cell phones. Indeed, Nokia already offers a phone with RFID reading capability.

    RFID is a collection of technologies centered around transmitting small amounts of data via low-energy radio frequencies. An RFID tag consists of a microchip capable of storing around 2 KB of data, sufficient to encode basic information about an object, such as its serial number or manufacturer name. Recent RFID tags often contain just a single 96-bit number, or product "license plate," that serves as a globally unique ID for the tagged object. Attached to that microchip is a tiny radio antenna that helps communicate with a nearby RFID reader device.

    The least expensive RFID chips are read-only, with information imprinted in them during manufacture. More sophisticated RFID chips can be write-once/read-many, or even fully read-write capable. Chips that allow writing contain a header with a unique, non-erasable serial number, and some may even be programmed to restrict further write access.

    Depending on the type of RFID tag, a reader device can access information in the tag from a distance of between a foot to several hundred feet. Difference in RFID read range is mostly due to whether a tag contains its own power source (active tag), or whether it derives its energy entirely from the electromagnetic field of the reader device (passive tag). Passive tags cost much less to manufacture, but require readers in close proximity.

    To further reduce RFID tag manufacturing costs, instead of microchips, some RFID tags use plastics or conductive polymers to store data. And some tags don't even store data: Using special plastics, they reflect back to the reader only a well-defined portion of the radio waves targeted at them. The reader device captures those waves and computes the tag's identity based on what frequencies it received back.

    While recent RFID applications each defined their own data formats, several industry consortia are working on standardizing the kinds of data recorded on RFID tags. Such standards will allow RFID-aware applications to work across organizational boundaries and even business domains. For instance, standard tag formats for personal medical records data might improve the sharing of electronic medical records, and even encourage the use of RFID chips implemented in the body for the purpose of facilitating instant access to potentially life-saving data. An example for such standardization is the Electronic Product Code initiative that aims to provide unique identifiers for any product in any industry that manages a supply chain[5].

    In addition to standardized information on a tag, an equally important standardization effort aims to define the data-packaging format to exchange information between a reader and an RFID tag. Having such a standard format allows an RFID application to communicate with any device supporting that data exchange specification, regardless of the type of device. The Java Contactless Communication API follows the data exchange format currently being defined by the Near Field Communication (NFC) Forum[6]. The NFC specification encompasses a variety of near-field communication devices. Therefore an application using the Java Contactless Communication API would not have to care whether the discovered target is an RFID tag or some other NFC-adhering contactless target.

    Reading From a Contactless Target

    The concluding section of this article illustrates reading information from a contactless target. Such a target may be an RFID tag, or a cell phone capable of near-field communication. The only requirement the Contactless Communication API imposes on a device is that the device support the NFC communication standard.

    Discovery of a nearby contactless target and reading data from that target is based on an event-driven programming model. That model will be thoroughly familiar to Jini developers. First, an application must register interest in newly discovered targets via a DiscoveryManager. When the DiscoveryManager discovers a new target, it invokes each of its TargetListener's targetDetected() method, passing in an array of TargetPropertys. Each element in that array represents a newly discovered target. Each TargetProperty, in turn, includes a URL representing a connection endpoint with the newly discovered device.

    Since the URL to the device indicates the desired communication protocol, a handler for that protocol must be available to contact the newly discovered device. The Java Contactless Communication API does not care of the specific protocol used, and relegates protocol-level communication details to the J2ME general connection framework. Once a connection is established, the contents of that connection can be retrieved, including the service records stored on the device.

    The following code snippet, taken from the Draft Specification version, illustrates reading an array of ServiceRecords from a device:

    
    public class CCAPIExample implements TargetListener {
       
       private DiscoveryManager dm; 
       private ContactlessConnection conn = null;
    
       public CCAPIExample() {
       
          // Get DiscoveryManager instance and set TargetListener for RFID_TAG targets
           dm = DiscoveryManager.getInstance();
    
           try {
             dm.addTargetListener(this, TargetType.NFC_TAG);
          }
           catch (IOException ce) {
              // Handle exception
          }
       }
    
       public void targetDetected(TargetProperties[] prop) {
         
         // If multiple targets discovered -> return
         if (prop.length > 1) {
            System.out.println("Multiple targets found");
            return;
          }
    
         // Only one target found
         TargetProperties target = prop[0];
    
         try {
    
           // Open ContactlessConnetion to target
           conn = (ContactlessConnection)Connector.open(target.getUrl());
    
           // Get the content of the target
           NFCContainer container = conn.read(false);
           ServiceRecord[] records = container.getRecords();
           ...
         }
         catch (IOException ioe) {
           // Handle exception
         }
         catch (ContactlessException ce) {
           // Handle exception
         }
       }
    }
    
    

    The resulting ServiceRecord class contains the name of the service record, and a byte array representing the record data. The meaning of that data is specific to an application. Recently emerging standards aim to specify records formats for a variety of applications. An application interested in contactless communication events would inspect the discovered service records and, if those records are of interest to the application, perform appropriate actions.

    For example, such a record may represent the product identifier for a milk box, and may be attached to the box itself in an RFID tag. A consumer browsing a supermarket shelf could use an application on an RFID-capable cell phone to retrieve that product code and fetch nutritional or allergy-related information about the milk product. If a variety of products on that supermarket shelf sport similar RFID-embedded product codes, the mobile phone application can suggest the type of milk best matching the customer's nutritional profile or exercise regimen.

    While the above code conveniently ignores exception handling, exceptions due to network failures are common occurrence in contactless communication, because devices may change position and move out of range at any moment. Thus, reading from a contactless communication may result in an IOException or ContactlessException that an application must deal with.

    Summary

    While this article thus far focused on the Contactless Communication API's ability to read RFID tags, the initial version of the API is designed to process barcode data as well. Barcodes are already ubiquitously imprinted on almost every consumer goods package, and even on some books and magazines. The Contactless Communication API enables camera phones to read and process such barcodes: You'd simply point your phone's camera to the barcode and launch a Contactless Communication-enabled Java application. Such an application could use a mobile version of the Java 2D API to process the graphics snapshot of the barcode, and hand that information over the Contactless API for further processing. From an application's point of view, reading the barcode via the API is similar to reading data from any contactless target.

    The Contactless Communication API is currently in Public Draft Review stage in the JCP. Because the specification depends to a great extent on the NFC Forum's data format definitions, final form of this spec may have to wait until the NFC data formats firm up. However, that wait may be acceptable, since applications taking advantage of the convergence of multimedia and RFID-enabled cell phones and intelligent product identification are only now starting emerge. The Contactless Communication API will likely contribute to the proliferation of such applications, since it presents the variety of contactless targets via a simple, homogeneous interface to Java

    Resources

    [1] A podcast of Bill Joy's talk at the 2005 MIT Emerging Technologies Forum.
    http://podcast.technologyreview.com/mit/joy.m4a

    [2] Java Contactless Communication API, JSR 257
    http://www.jcp.org/en/jsr/detail?id=257

    [3] For more information about RFID, see:
    http://www.rfidjournal.com/

    [4] The Jini Community's Web site
    http://www.jini.org

    [5] Electronic Product Codes
    http://www.epcglobalinc.org

    [6] Near-Field Communication Forum
    http://www.nfc-forum.org/home

    See also:

    Infrared Java API. (No updates since 2000)
    http://www.hpl.hp.com/personal/Jean_Tourrilhes/IrDA/Java.html

    This Explorer for Nokia phones allows you to manipulate and send files via Bluetooth and infrared
    http://www.my-symbian.com/7650/applications/applications.php?faq=2&fldAuto=199

    Embedded Java Resouces
    http://www.geocities.com/sherry_a_nelson/EmbeddedJava

    Java Bluetooth
    http://www.javabluetooth.com/development_kits.html

    Java BlueTooth API
    http://www.jcp.org/en/jsr/detail?id=82

Talk back!

Have an opinion? Be the first to post a comment about this article.

About the author

Frank Sommers is an editor with Artima Developer. He is also founder and president of Autospaces, Inc., a company providing collaboration and workflow tools in the financial services industry.