Creating an application

Creating an application means that you're allowing an actual application or service to connect to a specific Watson IoT Platform organization:

  1. In order to do that, access the IoT organization through the IBM Cloud dashboard, select Apps from the side menu, then select Generate API key and fill in the Description field with Hands-On IoT Solutions with Blockchain - Chapter 1 App. Finally, click on Next:
  1. Select the Standard Application role and click on Generate Key. You will get an API Key and Authentication Token. Make a note of these in a table format, like the one that follows, as you'll need them to connect to your application:
  1. Next, open the IDE of your preference, create a new Node.js project, and install the ibmiotf dependency package:
npm install ibmiotf --save
  1. Ensure that your package.json file looks something like the following:
{
"name": "sample-application",
"version": "1.0.0",
"description": "Hands-On IoT Solutions with Blockchain - Chapter 1 App",
"main": "index.js",
"scripts": {
"start": "node .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Maximiliano Santos",
"license": "ISC",
"dependencies": {
"ibmiotf": "^0.2.41"
}
}
  1. Now, create a file named application.json with the following content:
{
"org": "<your iot org id>",
"id": "<any application name>",
"auth-key": "<application authentication key>",
"auth-token": "<application authentication token>"
}
  1. Create a file named index.js and add the following content:
var Client = require("ibmiotf");
var appClientConfig = require("./application.json");

var appClient = new Client.IotfApplication(appClientConfig);

appClient.connect();

appClient.on("connect", function () {
console.log("connected");
});
  1. The application can be tested by running the npm start command:
$ npm start
> sample-application@1.0.0 start /sample-application
> node .
connected

Congratulations, you just created your first application connected to IBM Watson IoT Platform!

  1. Now, update index.js to have the following content:
var Client = require("ibmiotf");
var appClientConfig = require("./application.json");

var appClient = new Client.IotfApplication(appClientConfig);

appClient.connect();

appClient.on("connect", function () {
appClient.subscribeToDeviceEvents();
});

appClient.on("deviceEvent", function (deviceType, deviceId, payload, topic) {
console.log("Device events from : " + deviceType + " : " + deviceId + " with payload : " + payload);
});

Now, whenever a device publishes an event, you will get the event printed to stdout. In the next section, we will create a device to publish the events.