Overview

Skill Level: Any Skill Level

Beginner

Ingredients

Basic knowledge of Eclipse Kura and OSGi

Eclipse Kura runtime on any target platform

Eclipse IDE

Bluemix account and basic knowing

 

 

 

Step-by-step

  1. Introduction

    Eclipse Kura is an OSGi based framework that provides a platform for building IoT gateways. It is a smart application container that enables remote management of such gateways and provides a wide range of APIs for allowing you to write and deploy your own IoT application. For a general introduction and more details please visit http://eclipse.github.io/kura/doc/intro.html.

    Kura was originally developed by Eurotech and later was contributed to the Eclipse community becoming an Open Source project licensed under EPL. Its roots are still apparent – Kura’s CloudService still shows specifics meant to interact with Eurotech’s Everywhere Device Cloud (EDC). These specifics are not compatible with other IoT cloud services like IBM Watson IoT:

    • the MQTT message payload encoding is based on Google protocol buffer – a binary serialization format for structured data
    • the messages are optionally compressed
    • EDC specific topic prefixes
    • default subscription to EDC specific topics for remote device management

    This recipe describes how you can still successfully connect to the Watson IoT service by bypassing the CloudService and use the more general DataService instead to send MQTT messages.

    Note: This tutorial is based on Eclipse Kura version 1.4

  2. Preparations

    Install Kura runtime and development environment

    If not already done, first ensure you have completed the following steps:

    Register your device on the Watson IoT Platform

    Once you have access to the Watson IoT platform organization through Bluemix, you can click ‘Add a new device’ on the IoT organization dashboard.

    During the device registration process you will get configuration information containing the following details. Record these details carefully, you will need them again later.

    Organization ID (OrgID)
    Device Type ID (DevType)
    Device ID (DevID)
    Authentication Method
    Authentication Token

  3. Create a new OSGi bundle project

    Follow this tutorial https://eclipse.github.io/kura/doc/hello-example.html

    • Name the project org.eclipse.kura.example.hello_watsoniot
    • Do not forget to select OSGi framework standard
    • Name class HelloWatsonIoT
    • Do not forget to append OSGI-INF to the parent folder path when creating the component definition
    • Export the project as OSGi Bundle a simple jar (not as deployment Package) and store it on your local disc
    • Deploy the new bundle to Kura, either by command line tools or by using the Eclipse mToolkit plug-in:

    The new bundle now should show up on Kura Web UI under System/Device, Bundles Tab and is reported to be active:

    Now let’s flesh out the skeleton with some more functionality.

  4. Add DataService to the project

    Add a reference to the DataService

    • Double-click the Component.xml file under OSGI-INF in the Package Explorer
    • Select the Tab Services and click on “Add…” within the Referenced Servicessection
    • Type in org.eclipse.kura.data and click OK
    • Click the Edit… button
    • Add bindings setDataService and unsetDataService
    • Save component.xml file

    Add dependency to data service package

    • Double-click the MANIFEST.MF file in the Project Explorer
    • Select the Dependencies Tab, click on Add… under the Imported Packages section
    • Type in org.eclipse.kura.data and click on OK
    • Save Manifest file

    Extend the Java class HelloWatsonIoT by the functions to bind/unbind the DataService

    class HelloWatsonIoT {

    […]

    private DataService m_dataService;

    public void setDataService(DataService dataService) {
    m_dataService = dataService;
    }

    public void unsetDataService(DataService dataService) {
    m_dataService = null;
    }

    […]
    }

    Ensure, that the function names exactly match the names you entered above when editing the bind/unbind fields of the DataService reference. The framework automatically calls these functions to provide a reference to the DataService at runtime.

    Note: Since the DataService is later configured to connect and re-connect automatically, we do not need to establish a connection in the code explicitly.

  5. Add a worker thread for continuous publishing

    Add two new member variables to the class:

    class HelloWatsonIoT {
    [...]
    private ScheduledExecutorService m_worker;
    private ScheduledFuture<?> m_handle;
    [...]
    }

    In the activate() function of the class, initialize and start the worker which is triggered every 3 seconds:

     // schedule a new worker triggered every 3 seconds
    m_worker = Executors.newSingleThreadScheduledExecutor();
    m_handle = m_worker.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
    Thread.currentThread().setName(getClass().getSimpleName());
    doPublish();
    }
    }, 0, 3, TimeUnit.SECONDS);

    Ensure the worker is shutdown when the bundle is deactivated. Add this to the deactivate() function of the class:

     m_handle.cancel(true);
    m_worker.shutdown();

  6. Add the actual publishing function

    Implement the doPublish function. Here, we just publish a simple event with a random value as the actual payload.

    class HelloWatsonIoT {
    [...]
    private Random m_random = new Random();

    private void doPublish()
    {
    int randomNumber = m_random.nextInt(50);
    final String payload = "{ "d": { "Name" : "HelloWatsonIoT", "randomNumber" : " + randomNumber + "}}";
    final String topic = "iot-2/evt/event1/fmt/json";

    // Publish the message
    try {
    m_dataService.publish(topic, payload.getBytes(), 0 /* qos */, false /* retain */, 1 /* priority */);
    s_logger.info("Published to {} message: {}", topic, payload);
    }
    catch (Exception e) {
    s_logger.error("Cannot publish topic: "+ topic, e);
    }
    }

    [...]
    }

    The code is now complete. Before deploying the updated bundle, let’s reconfigure Kura in order to connect to Watson IoT.

  7. Configure MqttDataTransport Service for connecting to Watson IoT

    On the Kura Web UI, select the MqttDataTransport service and update the following fields:

    • broker-url with mqtt://jn0mo4.messaging.internetofthings.ibmcloud.com:1883
    • username with use-token-auth
    • password with the authentication token as generated and displayed when you setup your device on Bluemix Watson IoT
    • client-id with a combination of the orgID, DevType, DevID as given when you setup your device on Bluemix Watson IoT all separated by colons prefixed by the letter d (d:<orgID>:<DevType>:<DevID>)
    • clear field lwt.topic

    Note: For Kura version 1.4 it shows that lwt.topic is automatically reset to the default value on next startup of Kura in case of lwt.topic has been set to an empty value.

  8. Enable DataService auto connect

    • On the Kura Web UI, select the DataService
    • For the field connect.auto-on-startup, select true
      • this causes the DataService to ensure a permanent connection to the MQTT broker. It will also automatically re-connect in case of connection loss.

  9. Disable CloudService

    As mentioned earlier, the CloudService is EDC specific and not appropriate for connecting to Watson IoT. Even though our bundle is actually not using it, it is still active and intercepts any connection. For this reason it needs to be deactivated.

    • On the Kura Web UI, select Device, then tab Bundles
    • Select bundle named org.eclipse.kura.core.cloud and click on Stop
    • Confirm to stop the service.

    Note: This will not permanently deactivate the CloudService on next restart of Kura it is active again. To permanently disable the service, edit the Kura config.ini file (Example location: /opt/eclipse/kura/kura) and modify the osgi.bundles parameter by changing the action for the ../kura/plugins/org.eclipse.kura.core.cloud_*.jar from start to stop.

  10. Deploy and run the completed version of HelloWatsonIoT Bundle

    Now that Kura has been configured to be ready for connecting to Watson IoT, you can deploy the completed version of your HelloWatsonIot Bundle and start it.

    Note: Deploying a single bundle via the mToolKit Eclipse plug-in will not permanently install the bundle on next startup of Kura it is gone. For permanent installation follow the instructions Making Deployment Permanent that you will find at the bottom of https://eclipse.github.io/kura/doc/deploying-bundles.html#_Install_Single_Bundle

    In the /var/log/kura.log file you now shoud see the following lines repeating every 3 seconds:

    2016-03-26 17:19:05,937 [] INFO o.e.k.e.h.HelloWatsonIoT - Published to iot-2/evt/event1/fmt/json message: { "d": { "Name" : "HelloWatsonIoT", "randomNumber" : 2}}
    2016-03-26 17:19:05,941 [DataServiceImpl:Submit] INFO o.e.k.c.d.t.m.MqttDataTransport - Publishing message on topic: iot-2/evt/event1/fmt/json with QoS: 02016-03-26 17:19:05,937 [] INFO o.e.k.e.h.HelloWatsonIoT - Published to iot-2/evt/event1/fmt/json message: { "d": { "Name" : "HelloWatsonIoT", "randomNumber" : 2}}
    2016-03-26 17:19:05,941 [DataServiceImpl:Submit] INFO o.e.k.c.d.t.m.MqttDataTransport - Publishing message on topic: iot-2/evt/event1/fmt/json with QoS: 0

    Now check that the messages in fact are received by Watson IoT:

    • Login to Bluemix
    • Select the Watson IoT service
    • Navigate to the dashboard
    • Click on Devices
    • In the Devices overview table, click on your device
    • Here you should be able to see the incoming events under Recent Events and Sensor Information

Join The Discussion