Working with Worklight: Part 3: Enhancing the Todo app using the MQTT protocol

This series of articles introduces the IBM Worklight platform by showing how you can build mobile apps that leverage a variety of IBM software products. Part 3 shows you how to enhance the sample Todo Worklight app by using the MQTT protocol to share items between app users.

Carlos Andreu , Software Developer, IBM Software Group, IBM

Carlos Andreu is a Software Developer in IBM Software Group. He is currently working on the creation of a framework to build Hybrid, Android and iOS apps. His interests range from following the latest trends and tech blogs, to reading, television, and enjoying to all kinds of music. You can learn more about Carlos on yapr.org or contact him at cnandreu@us.ibm.com.



Raj Balasubramanian, Consulting IT Architect, IBM Mobile Foundation, IBM

Raj Balasubramanian is a Consulting IT Architect, focusing on IBM Mobile Foundation and IBM Worklight implementations. Previously he led customer engagements related to BPM, Portal, SOA, and Web 2.0. His interests range from anything technical to history, math, and physics. He is currently pursuing his PhD at the University of Texas at Austin. You can read about Raj's technical and personal escapades on his blog at Gurukulam, or can contact him at raj_balasubramanian@us.ibm.com.



Jeremy Nortey, Software Developer, IBM Mobile Foundation , IBM

Jeremy Nortey is a Software Developer for IBM Mobile Foundation within Software Group. He develops software and quality assurance for mobile solutions. He specializes in iOS and dabbles in building native apps for the iPhone in his spare time. His hobbies include soccer and running. You can contact Jeremy at janortey@us.ibm.com.



20 March 2013

Also available in Japanese

Introduction

As you saw in Parts 1 and 2 of this article series, IBM® Worklight provides a robust platform for building mobile apps that leverage web-based technologies and run across multiple device platforms. Part 3 will show you how to extend the Todo Worklight app by enabling users to collaborate by subscribing to each others to-do items.

About MQTT and RSMB

Message Queue Telemetry Transport (MQTT) is an open-source, lightweight messaging protocol that enables messaging between remote locations with a very small memory and bandwidth footprint. It uses the publish/subscribe messaging model and is ideal for mobile devices because of its low power usage and its support for an alternative to push notifications.

Really Small Message Broker (RSMB) is an open-source, lightweight, low-overhead message broker that uses the MQTT protocol to transport messages across a network. In RSMB, clients subscribe to topics stored on the broker, and it pushes messages to each subscriber as the messages are received. The RSMB code takes up only about 80 KB of memory, and its operation typically consumes less than 200 KB, making it ideal for small servers and mobile devices.

Setting up the server infrastructure

  1. Download and run RSMB.
  2. Download the MQTT client, which will let you test RSMB running on your local machine in a GUI.
  3. After you have downloaded and extracted the file ia92, go into the J2SE folder and run the wmqttSample.jar file. A GUI will open to connect to RSMB running on your localhost (or you can change the hostname for RSMB).
  4. You can test your instance of RSMB by subscribing to and publishing to topics.

Configuring Todo app to use MQTT

Here is the life cycle of a to-do item:

Figure 1
Architecture of Todo app

The three components -- the Todo app running on the device, the Worklight runtime server, and RSMB -- work together to get a to-do item from the user and publish it to all other users. This flow is described in more detail below.

Using MQTT with Worklight Adapter

In order to publish messages to and subscribe to messages from RSMB, you need to call MQTT methods that are implemented in Java. Take advantage of an adapter's ability to call Java code in order to publish and subscribe to RSMB from the adapter, and then make remote calls from the Todo app to the Todo app to send or receive any new information.

In the ZIP file that contains the Todo project enhanced with MQTT, there is a custom Java class to enable a Worklight adapter to publish and subscribe to RSMB. This custom Java class includes the MQTT library (which is also included in the zip file) that enables you to make the necessary calls.

For more information on calling custom Java code from a Worklight adapter, see Module 5.5 – Using Java in Adapters in the IBM Worklight Getting Started documentation.

Worklight Adapter calling custom MQTT classes

In between the MQTT Java® classes and the Worklight app is the Worklight adapter, an HTTP adapter that is customized to:

  • Act as middleman when exchanging messages between the Todo app to RSMB.
  • Specify the host and port on which RSMB is running.
  • Maintain a persistent connection with RSMB so that messages can sent and received in real time.

Although the adapter sends and receives messages with RSMB in real time, the client must invoke the adapter in order to get any pending messages that the user is subscribed to. The app uses publish/subscribe to broadcast tasks from a users to their colleagues as they update their tasks. When the app first opens, it asks the user to specify their username, and then sends it to the adapter, which then contacts RSMB to create a new topic with the given username. After that, any items that the user adds to their to-do list is published to that topic.

If the user wishes to subscribe to other users, they enter the names in the Todo app. The names are sent to the adapter, which contacts RSMB in order to subscribe to the given usernames. After that, any messages published to that topic are sent to the user.

Understanding flows

MQTT uses the publish/subscribe model to sending and receive messages, as described above. The Todo app uses this model under the covers -- a topic is defined by each user's username, and users can receive other users todo items by subscribing to their topics. Here are brief explanations of three flows from the Todo app to RSMB and back:

Flow1

Flow1 describes the creation of the topic for User1, who enters their username in the Todo app and sends it to the adapter. The adapter then sends it to RSMB, which creates a new topic using the username, which other users can subscribe to in order to receive any todo items that User1 publishes:

Figure 2
Chart of Flow 1

Flow2

Flow2 describes the subscription to the topic created by User1. User2 enters the name of the user they want to subscribe to in order to receive any new updates from that user. The username is sent to the Worklight server, which sends it to RSMB. RSBM then creates a subscription for the topic, which enables User2 to receive any to-do items posted by User1.

Figure 3
Chart of Flow 2

Flow3

Flow 3 describes publishing and retrieving a to-do task after the topic has been created and subscribed to. User1 creates a to-do item, which is stored and displayed on his device and then sent to the Worklight adapter. The adapter then sends it to RSBM, which sends the message to all users subscribed to User1. User2, who has already subscribed to User1, opens his app and clicks Sync. The Worklight adapter already has any messages that User2 has subscribed to, so the Sync method pulls these pending messages from the Worklight server to the app's display.

Figure 4
Chart of Flow 3

Enhancing the Todo app

The following instructions show you how to add collaboration between users to the Todo app . You can use these instructions along with the downloadable source code in order to adapt it to accommodate your design needs.

Creating the Todo app UI

The modified Todo app consists of three pages:

  • Login page -- Lets user enter username, which is sent to the adapter, which then sends it to RSMB. RSMB then creates a new topic using the username, so that other users can subscribe to in order to receive future messages from that user:
    Figure 5
    Illustration of Login page
  • To-do page -- Displays current user's to-do items and lets user to sync with other users in order to view their to-do items:
    Figure 6
    Illustration of To-do page
  • Subscription page lets user subscribe to other users and view all current subscriptions:
    Figure 7
    Illustration of Subscription page

Creating the MQTT adapter

The Todo app needs a new adapter called MQTT_Adapter that implements the following procedures:

  • registerUser(username) -- Initializes the custom MQTT class that has been added to the server/lib folder. It then accepts the username passed from the current user and passes it to RSMB to create a new topic based on that username for other users to subscribe to.
  • publishItem(item) -- Publishes a new to-do item for the registered topic for the user. All other users who have subscribed to the current user's topic immediately receive any published message.
  • subscribeToUser(user) -- Subscribes to the topic for a user specified by the current user. Any subsequent messages that the specified user publishes are sent to the current user. The current user does not receive previously published messages published by the specified user.
  • sync() -- Gets all pending messages from the adapter for all topics that the current user has subscribed to. Even though the adapter receives all messages from RSMB immediately, the current user must invoke sync() in order to receive the messages. The implementations of each of these functions are wrappers around the Java MQTT classes that have been included in the server/lib folder of the Worklight project. Most of the logic behind these wrappers occurs in the custom Java class.

Calling appropriate adapter methods from the Todo app

As described below, each page calls one or more of the adapter methods in order to communicate with RSMB.

  • Login page -- When the user clicks Login, the username entered in the text field is passed to the adapter. The adapter then invokes custom Java code to create a new topic in RSMB with the username as the topic. After that, any other user can subscribe to that topic:
    /**********************************************************************************
    *                     Register User
    **********************************************************************************/
    function registerUser(username){
    
        var invocationData = {
            adapter : 'MQTT_Adapter',
            procedure : 'registerUser',
            parameters : [username]
        };
    
        WL.Client.invokeProcedure(invocationData, {
                onSuccess : registerUserSuccess,
                onFailure : registerUserFailure
            });
    }
    
    function registerUserSuccess(response){
        console.log("registerUser Success");
    }
    
    function registerUserFailure(response){
        console.log("registerUser Failure");
    }
  • Todo page -- When the user clicks Add item, an action occurs in the Todo app as well as in the adapter. First, the new to-do item is dynamically added to the table seen by the current user. Next, the new to-do item is sent to the adapter, which passes it on to RSMB. After that, any other users that have subscribed to this current user will receive the to-do item. Users who subscribe after the item was sent will not receive the message:
    /**********************************************************************************
    *                         Publish Item
    **********************************************************************************/
    function publishItem(item){
    
        var invocationData = {
            adapter : 'MQTT_Adapter',
            procedure : 'publishItem',
            parameters : [item]
        };
    
        WL.Client.invokeProcedure(invocationData, {
            onSuccess : publishItemsSuccess,
            onFailure : publishItemsFailure
        });
    }
    
    function publishItemsSuccess(response){
        console.log("publishItem Success");
        console.log(response);
    }
    
    function publishItemsFailure(response){
        console.log("publishItem Failure");
        console.log(response);
    }

    When the user clicks Sync, a call is made to the adapter to retrieve all messages from each topic that the current user has subscribed to. Even though the adapter is receiving all messages immediately as other users publish them, the Todo app must request the messages from the adapter. If the Java code were located on the Todo app, then there would be no need to make the adapter call, as you would be able to receive the messages immediately:

    /**********************************************************************************
    *                              Sync
    **********************************************************************************/
    function sync(){
        
        var invocationData = {
                adapter : 'MQTT_Adapter',
                procedure : 'sync',
                parameters : []
        };
        
        WL.Client.invokeProcedure(invocationData, {
            onSuccess : syncSuccess,
            onFailure : syncFailure
        });
    }
    
    function syncSuccess(response){
        console.log("sync Success");
        console.log(response);
        var returnedItems = response.invocationResult.items;
        
        for(var i=0; i<returnedItems.length; i++){
            addItemToList('#item_list', returnedItems[i]);
        }
    }
    
    function syncFailure(response){
        console.log("sync Failure");
        console.log(response);
    }
  • Subscribe page -- The Sync button on the todo page will not do anything unless you first subscribe to other active users. When the user clicks Subscribe on the Subscribe to Users page, the name in the text box is sent to the adapter, which subscribes to all subsequent to-do items posted by the specified user. The name that the current user subscribes to will be listed in the table shown on the Subscribe page:
    /**********************************************************************************
    *                          Subscribe To User
    **********************************************************************************/
    function subscribeToUser(user){
        
        var invocationData = {
                adapter : 'MQTT_Adapter',
                procedure : 'subscribeToUser',
                parameters : [user]
        };
        
        WL.Client.invokeProcedure(invocationData, {
            onSuccess : subscribeToUserSuccess,
            onFailure : subscribeToUserFailure
        });
    }
    
    function subscribeToUserSuccess(response){
        console.log("subscribeToUser Success");
        console.log(response);
    }
    
    function subscribeToUserFailure(response){
        console.log("subscribeToUser Failure");
        console.log(response);
    }

    This project used jQuery mobile as the framework for the design and user interface. The source code shows how the functions are connected to each UI element in the project. For example, here is the implementation for publishing a new item:

    $('#add_item').live('click', function(){
        var newItem = $("#new_item").val();
        $("#new_item").val('');
        addItemToList('#item_list', newItem);
        
        publishItem(newItem);
    });

    jQuery mobile is used to add the Click event to the button on the main HTML page with the id add_item. The Todo app then takes the value from the text box with the id new_item and calls the locally implemented function addItemToList in order to dynamically add this new item to a jQuery mobile list that has the id item_list. The app then calls the locally defined function publishItem and sends the new item to the adapter, so that RSMB can publish it to all subscribed users. The implementation for all other buttons is similar.

Conclusion

Part 3 of this article series showed you how to use MQTT and the publish/subscribe model to add collaboration capabilities in order to share tasks with colleagues. You can leverage this procedure to add other capabilities to your mobile apps built on Worklight. A future article will show you how to use MQTT from the client device to do the same task sharing directly from the client.


Download

DescriptionNameSize
Code sampleTodo-MQTT.zip2.5 MB

Resources

Learn

Get products and technologies

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Mobile development
ArticleID=860891
ArticleTitle=Working with Worklight: Part 3: Enhancing the Todo app using the MQTT protocol
publish-date=03202013