Explore the Internet of Things Platform service

The IBM IoT Platform provides simple, but powerful, services capable of interconnecting different kinds of devices and applications all over the world. The IoT Platform supports MQTT, the Message Queue Telemetry Transport, which is a lightweight and flexible network protocol. In this tutorial, you’ll see how you can easily build applications using the IoT service.

In MQTT terms, the IBM IoT Platform service acts as the broker, and is thus responsible for distributing messages to connected clients (devices and applications). Devices include machines that publish information they detect, and applications are the programs that consume the information received from those devices. Devices and applications communicate with the broker, as shown in Figure 1.

Figure 1. IBM Cloud (formerly IBM Cloud) services and MQTT clients
IBM Cloud IoT Service (MQTT broker) subscribes commands on the device side (MQTT client) and events on the application side (MQQT client).

An application using the IBM IoT Platform usually consists of three parts:

  • IBM IoT Platform service configuration (device and application registration)
  • Device-side programming
  • Application-side programming

Ready to give it a try?

What you’ll need to build your application

Step 1. Set up the IBM IoT Platform service

From the IBM Cloud console, click on Catalog, Internet of Things, and then select Internet of Things Platform. From here, you can choose a service plan. The Lite plan is free of charge and provides enough capability for most small projects.

Creating an instance of the IBM IoT Platform

Once you create an IoT platform service instance, you can click on the “Launch” button from the “manage” section to launch it.

Launching an instance of the IBM IoT Platform

Note down the “Organization ID” of your platform instance in the “Settings” screen. I have “za6xa7” for my Lite instance. The organization ID is also in the management console’s URL: https://za6xa7.internetofthings.ibmcloud.com/.

Settings for an instance of the IBM IoT Platform

Next, in the “Devices” section, you can create a new device. The device has a type and an ID. Here, we create a device of test type and 4321 ID.

Adding a device in instance of the IBM IoT Platform

Finally, you can create a standard application to receive and process messages from the device. Each application has an ID and an access token.

Creating an app in instance of the IBM IoT Platform

Step 2. Create a device-side program

Device-side programming consists of three parts:

  • Connecting to the IoT service (MQTT broker).
  • Publishing events to applications.
  • Subscribing commands from applications.

In this section, you’ll build a simple device-side program using the Python SDK in the ibm-watson-iot GitHub repo. For more information, see the source code.

Connect to the IoT service

The code here shows the structure of the device-side program. It connects to one of the Watson IoT Platform devices we created in the dashboard. The connection parameters are loaded from a YAML configuration file for the specific device.

import wiotp.sdk.device

options = wiotp.sdk.device.parseConfigFile("device_4321.yaml")
client = wiotp.sdk.device.DeviceClient(options)
client.connect()
# do things
client.disconnect()

The YAML file for device ID 4321 is as follows. Notice that it configures the messaging.pem certificate file to enable TLS encrypted connection to the IBM IoT Platform service.

identity:
    orgId: za6xa7
    typeId: test
    deviceId: 4321
auth:
    token: mytesttoken4321
options:
    domain: internetofthings.ibmcloud.com
    logLevel: debug
    http:
        verify: True
    mqtt:
        port: 8883
        transport: tcp
        cleanStart: true
        sessionExpiry: 7200
        keepAlive: 120
        caFile: /home/ubuntu/ibmiot/messaging.pem

Publish events

The main function of an IoT sensor device is to collect and send data to backend applications. The IBM IoT Platform is responsible for broadcasting the event to all applications that listens for device events.

import wiotp.sdk.device

options = wiotp.sdk.device.parseConfigFile("device_4321.yaml")
client = wiotp.sdk.device.DeviceClient(options)

def eventPublishCallback():
    print("Device Publish Event done!!!")

client.connect()
myData={'mesg' : 'Hello World'}
client.publishEvent("status", "json", myData, 0, eventPublishCallback)
client.disconnect()

Subscribe commands

After connection to the device on IBM IoT Platform, our device is now ready to receive commands from an application registered in the same IBM IoT Platform service. The program below registers a callback function for commands. The device then waits for commands, and processes each received command in the callback function.

import wiotp.sdk.device
import time
import json
import signal
import sys
import logging

def myCommandCallback(cmd):
    print("Command received: %s" % cmd.data)

def interruptHandler(signal, frame):
    client.disconnect()
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, interruptHandler)

    options = wiotp.sdk.device.parseConfigFile("device_4321.yaml")
    client = wiotp.sdk.device.DeviceClient(options)

    client.logger.setLevel(logging.DEBUG)
    client.connect()
client.commandCallback = myCommandCallback

while True:
    time.sleep(1)

Step 3. Create an application-side program

As with device-side programming, application-side programming consists of three parts:

  • Connecting to the IoT service (MQTT broker).
  • Subscribing to events from devices or from applications.
  • Publishing commands to devices.

In this section, you’ll build a simple application-side program using the Python SDK in the ibm-watson-iot GitHub repo. For more information, see the source code.

Connect to the IoT service

The code here shows the structure of the application-side program. It connects to one of the Watson IoT Platform applications we created in the dashboard. The connection parameters are loaded from a YAML configuration file for the specific application.

import wiotp.sdk.application

options = wiotp.sdk.application.parseConfigFile("app_test1.yaml")
client = wiotp.sdk.application.ApplicationClient(options)
client.connect()
# do things
client.disconnect()

The YAML file for application ID test1 is as follows. Notice that it configures the messaging.pem certificate file to enable TLS encrypted connection to the IBM IoT Platform service.

identity:
    appId: test1
auth:
    key: a-za6xa7-lxmzussonj
    token: ag3kFHw?xIw_9hMOSo
options:
    domain: internetofthings.ibmcloud.com
    logLevel: debug
    http:
        verify: True
    mqtt:
        port: 8883
        transport: tcp
        cleanStart: true
        sessionExpiry: 7200
        keepAlive: 120
        caFile: /home/ubuntu/ibmiot/messaging.pem

Subscribe to events

After connection to the application on IBM IoT Platform, our application is now ready to receive events from devices and applications registered in the same IBM IoT Platform service. The program below registers a callback function for events. The application then waits for events in the specified queue, and processes each received event in the callback function.

import wiotp.sdk.application
import time
import json
import signal
import sys
import logging

def myEventCallback(event):
    str = "%s event '%s' received from device [%s]: %s"
    print(str % (event.format, event.eventId, event.device, json.dumps(event.data)))

def interruptHandler(signal, frame):
    client.disconnect()
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, interruptHandler)

    options = wiotp.sdk.application.parseConfigFile("app_test2.yaml")
    client = wiotp.sdk.application.ApplicationClient(options)

client.connect()
client.deviceEventCallback = myEventCallback
    client.subscribeToDeviceEvents()

    while True:
        time.sleep(1)

Send commands

To send a reboot command to the device, we use the IBM IoT Platform service to relay the command.

import wiotp.sdk.application

options = wiotp.sdk.application.parseConfigFile("app_test2.yaml")
client = wiotp.sdk.application.ApplicationClient(options)

client.connect()
myData={'rebootDelay' : 50}
client.publishCommand("test", "4321", "reboot", "json", myData)
client.disconnect()

Step 4. Run the programs

In this section, we demonstrate how to run the Python programs to send an event from a device to an application, and to send a command from an application to a device.

Events

First, start the application to listen for events for a device queue.

$ python application/app_event_receiver.py

The application waits. Next, run the device program to send an event from the device.

$ python device/device_event_sender.py

The application should receive the event and print it in the console

Commands

First, start the device program to listen for commands for this device.

$ python device/device_command_receiver.py

The device waits. Next, run the application to send a command for the device.

$ python application/app_command_sender.py

The device should receive the command and print it in the console.

Conclusion and next steps

By following these steps, you can build an app using the IBM IoT Platform service. If you are familiar with MQTT client programming, you might find there are no significant differences. Of course, when using the IBM IoT Platform service you must make properties — such as the MQTT connection options, publishing and subscription subjects form, connection security and so on — conform to the correct format.

It is easy to build solutions using the IBM IoT Platform service when they are based on an existing MQTT client library. The good news is that there are quite a number of open source MQTT client libraries for different platforms, such as C, C++, Java, JavaScript, Ruby, Go, and more. There are also several client libraries specific to Watson IoT Platform, as the Java library we used in this tutorial.

IBM IoT Platform services support a variety of connected smart devices, such as Arduino Uno, Raspberry Pi, and so on. There are several sample code projects in the documentation section of the web portal you can study. The previously discussed MQTT mechanism should help you understand and modify the source code. If your device is not covered in the sample code, don’t worry. Just as we implemented the device-side program in Python in this sample app, you can easily build your own program using an MQTT client library.

We implemented this application-side program in Python, but you might choose another programming language, such as Node.js or Java or C. To ease the application-side programming, you can use the browser-based flow editor Node-RED instead of coding it locally. Whether you are building it yourself or using Node-RED, the MQTT flow under the IBM IoT Platform service works the same way.

Acknowledgements

This article was originally written by Chun Bin Tang and published on February 18, 2015.

Michael Yuan