Overview

Skill Level: Beginner

Beginner

Introduction Node-RED is a tool for wiring together the Internet of Things in new and interesting ways, including hardware devices, APIs, and online services. It is built on top of Node.js and takes advantage of the huge node module ecosystem to provide a tool that is capable of integrating many different systems. Its lightweight nature […]

Ingredients

Step-by-step

  1. Introduction

     Node-RED is a tool for wiring together the Internet of Things in new and interesting ways, including hardware devices, APIs, and online services. It is built on top of Node.js and takes advantage of the huge node module ecosystem to provide a tool that is capable of integrating many different systems. Its lightweight nature makes it ideal to run at the edge of the network as well, such as on the Raspberry Pi, and other hack-friendly platforms.

    Node-RED contains the following Watson IoT nodes that helps you to connect your devices, gateways and applications to Watson IoT Platform and create IoT solutions quickly.

    • Watson IoT Node – A pair of nodes for connecting your device or gateway to the IBM Watson Internet of Things Platform. A device or gateway can use these nodes to send events and receive commands from the application.
    • IBM IoT App Node – A pair of nodes for connecting your application to Watson IoT Platform. An application can use these nodes to receive device events and send commands back to the device.

    In this recipe, you will learn the following,

    • How to configure the Watson IoT Output node to send device events to Watson IoT Platform.
    • How to configure the IBM IoT App In node to receive the device events.
    • How to configure the IBM IoT App Out node to send commands back to the device when the readings cross the threshold.
    • How to configure the Watson IoT Input node to receive the commands from the application

     

    What is demonstrated in this recipe?

    In this recipe, we will simulate a temperature device using the Watson IoT Node that will send the temperature readings to Watson IoT platform every 1 second. An application will subscribe to these temperature events and trigger a shut down command when the temperature crosses 30 degree Celsius.

  2. Setup Watson IoT Platform and Node-RED service on Bluemix

    One can install Node-RED locally on the laptop or any devices like Raspberry Pi to send sensor readings to Watson IoT Platform. Refer to the recipe, Connecting Raspberry Pi as a Device to Watson IoT Platform using Node-RED to use Node-RED on a Raspberry Pi to connect to Watson IoT Platform and send sensor data. Similarly follow the steps present in this tutorial to install Node-RED locally on your laptop and add Watson IoT and IBM IoT App nodes.

    Click on the Create Toolchain button provided below, to quickly deploy the Watson IoT Platform – Node-RED Bluemix starter app. Post successful deployment, you shall have both the above mentioned services, up & running on Bluemix along with a Cloudant NoSQL DB at your disposal.

    Toolchain-8

    Note: If you are a User using the United Kingdom Region in your Bluemix environment, then please make use of the steps mentioned in the IoT Recipe Deploy Internet of Things Platform Starter service on Bluemix to deploy the setup. Alternatively, you can also try using the Deploy to Bluemix button, to deploy the setup under your United Kingdom Region, provided your Jazzhub account is validated. Users of US South Region can ignore this step.

    deploy

    In this section, we detail how to include the Watson IoT node into the Bluemix Node-RED environment so that one can use the Bluemix environment itself to simulate the device.

    Access the Node-RED application

    Access the Node-RED application by clicking on the View App option available, post deploying your application and then choosing the option Go to you Node-RED flow editor, to access the editor.

    Parallelly, you can also access the Node-RED editor directly by accessing the following URL

     http://<your-application-name>.mybluemix.net/red

    The Node-RED editor has the default set of nodes and in the scope of this Recipe, you would need Watson IoT Node(s), as well.

     

    Include Watson IoT Nodes into Node-RED

    You can skip this section in case if you have installed Node-RED on your laptop or on your IoT device.

    • Click on the Git link as shown below to access the Git repository that is associated with this Node-RED application,

      Choose_Github_link-1

    • Choose package.json file and click on Edit to add the following line and have the Watson IoT node installed.
       "node-red-contrib-ibm-watson-iot":"0.x"
    • Below is the sample screenshot showcasing the code changes,

      PackageJson

      Note: You might be prompted to provide SSH Keys to Push the changes made to the package.json file (or any other edits to the Application)

    • Commit the changes,
    • Once the changes are Pushed through Commit operation, the Build & Deploy process gets initiated. You can choose to observe the log in the Delivery Pipeline option.
    • Once the deploy operation is successful, open the Node-RED application (refresh if its opened already) to see the Watson IoT input and output nodes.

    In this step, We have successfully created a Node-RED application in Bluemix and added a Watson IoT Node in it.

  3. Register your Device

    In order to send events to the Watson IoT Platform, you must first register your device on the platform.

    Open the Bluemix Dashboard and click on the Application service that you have currently deployed (using the Create Toolchain button), if you have already moved away from it. You should see the Watson IoT Platform listed under the Binded Services. Click on the WIoTP service and choose the click on Launch button to launch the WIoTP Dashboard.

    Carry out the steps present in this recipe to register your device(s) in IBM Watson Internet of Things Platform. Once complete, you will be presented with the device credentials as shown below. Make a note of them as you will need them in the following steps.

    Generate API Key and Token of Watson IoT Platform

    In order to connect the Node-RED application to IBM Watson IoT Platform to receive device events and send commands, we need to generate the API key and token first. This can be achieved by carrying out the steps mentioned in this section – Steps to generate API Key in Watson IoT Platform.

    At this step, we have successfully created the Watson IoT service and registered your device(s) in it.

  4. Simulate a Temperature Device

     In this step, we will configure the Watson IoT Out Node to send a temperature reading every second to Watson IoT Platform.

    • Go to your device’s Node-RED application, Drag and drop inject node from the input, double-click and configure the interval time as 1 second,
    • This will trigger the flow every 1 second, you can increase the time to a higher value as well.
    • Drag and drop a function node, double-click the node and paste the following code. This code creates a random temperature between 15 to 32 degrees. You can write your own code in the function area to change the temperature values or pull the data from the connected sensor,
      // Array of pseudo random temperatures
      var temp1 = [15,17,18.5,20,21.5,23,24,22.2,19,32];

      // Array of pseudo random relative humidities
      var humidity1 = [50,55,61,68,65,60,53,49,45,47];

      // Counter to select from array.
      var counter1 = context.get('counter1')||0;
      counter1 = counter1+1;
      if(counter1 > 9) counter1 = 0;
      context.set('counter1',counter1);

      // Create MQTT message in JSON
      msg = {
      payload: JSON.stringify(
      {
      d:{
      "temperature" : temp1[counter1],
      "humidity" : humidity1[counter1] }
      }
      )
      };
      return msg;
    • As shown, the above code sends humidity readings along with the temperature readings. Connect the nodes as shown below,
    • Add a Watson IoT Output node and configure it as follows:
      • Connect as Device in Registered mode
      • Add wiot-credentials by providing credentials obtained in the previous step
      • Set the Event type to temp as shown below,

    • Wire the output of the function node to the Watson IoT Output node. Also, attach a debug node to the output of the function node to view the payload in the debug panel. The complete flow should look like the following,
    • Click Deploy in the top right corner of the Node-RED flow editor window to deploy this flow. This will start sending the temperature event to Watson IoT Platform every one second, also outputs the event in the debug panel.

    This completes the device flow. In the next step, we will create an application flow to receive the event and process it.

  5. Add a Node-RED application to receive events from the device

    With events now being sent to Watson IoT, the next step is to create an application in Bluemix to receive the events.

    Create a simple flow to start receiving the device events

    • In case you are using the same Node-RED application for both device and application, create a separate sheet in the Node-RED editor for the application to distinguish the application flow from the device flow.
    • Add an ibmiot input node and configure it to use Bluemix Service authentication. Set the Device Type field to match the type you used to register your device with. Leave the Device Id and Event fields set to all.
    • Drag-n-Drop a function node, double click and paste the following code in the body to to extract the temperature value from the payload.
       return {payload:msg.payload.d.temperature};
    • Connect the output of ibmiot node to the input of function node.
    • Attach the debug node to the function node as shown below to print the extracted temperature value in the debug panel.
    • Click Deploy to deploy the flow in Node-RED and observe that the temperature readings are printed in the console.

    In this step, we have successfully configured the IBM IoT App In Node to receive the temperature reading from the Watson IoT Platform.

  6. Analyze temperature data

    In this step we will use the switch node to analyze the temperature and classify it as safe or unsafe.

    • Drag-n-Drop switch node from the function pane and create rules as shown below.
    • As shown, it creates 2 rules based on the temperature value. Temperature value equal to or below 30 flows through route 1 and temperatures above flows through route 2.
    • Drag-n-Drop a template node, double click and add the following message to format the output message,
      Temperature ({{payload}}) within safe limits 
    • Connect the 1st route (safe temperature route) of the switch node to this new template node as shown below,
    • Drag-n-Drop another template node for the abnormal temperature route, double click and add the following message to format the output message,
      Temperature ({{payload}}) critical 
    • Connect the 2nd route(abnormal temperature route) of the switch node to this new template node.
    • Drag-n-Drop the debug node and connect the output of both template nodes to it as shown below,
    • Click deploy and observe the temperature status in the debug panel as the device event is received.

    In this step we have successfully analyzed the temperature data and classified them as safe or unsafe.

  7. Send commands to your device

    In this step, we will send a shutdown command back to the device when the temperature is beyond the threshold.

    • Drag-n-Drop a function node to configure the “shutdown trigger“. And connect it to the second output ofclassify node. Paste the below code to send the command to the device when the temperature rises above 30 degrees.
      msg.payload=JSON.stringify({"data":"Shutdown"});
      return msg;
    • Drag and drop ibmiot node from the output pane. Configure it with the same api keys and device Id. Set the Output type as Device Command. And connect it to the shutdown trigger node as shown below,
    • The flow should look like the following now,
    • Click deploy to deploy the flow and it sends the command to the device whenever the temperature crosses the threshold.

    In this step, we saw how to send a command to the device when the threshold crosses a threshold.

  8. Receive commands on your device

    The final task is to create the flow on the device to handle the commands sent to it.

    • On your device’s Node-RED instance, add an Watson IoT Input node. Configure the node to connect as a Device, using the credentials you added previously and set to receive all commands. For example,
    • Attach a debug node to the Watson IoT Input node as shown below to output the commands into the debug panel,
    • Deploy the flow and observe the command whenever the temperature crosses 30 degrees.

    In this step, we saw how to receive a command on the device, which is sent by the application.

  9. Conclusion

    In this recipe, we learnt the following,

    • How to configure the Watson IoT Output node to send device events to Watson IoT Platform.
    • How to configure the IBM IoT App In node to receive the device events.
    • How to configure the IBM IoT App Out node to send commands back to the device when the readings cross the threshold.
    • How to configure the Watson IoT Input node to receive the commands from the application

    As a next step, go through the recipe Connecting a Sense HAT to Watson IoT using Node-RED to connect your Sense Hat to Watson IoT Platform.

  10. Next Steps

    Extend your hands-on experience with visualization and analytics on Watson IoT Platform:

10 comments on"Getting started with Watson IoT Platform using Node-RED"

  1. In Step 8, to receive commands on device, what should be the output selection in the debug node connected to the Watson IoT input node: message property or complete msg object?

    • YMDH_sathish_Palaniappan August 16, 2016

      The complete msg object will have other details like topic apart from the payload. the msg.payload will give you the exact payload (command) sent by the application.

  2. IBM IoT out node seems to have changed.
    Now if i select authehication: API KEY
    in API KEY I have to add:
    Name
    API Key
    API Token
    But when i register a device I have the following data:
    Organization ID
    Device Type
    Device ID
    Auth. method: token
    Auth. token:
    how i fill these record?

    • Thank you Pigio for the comments !

      Node-RED contains 2 Watson IoT nodes that helps one to connect their devices, gateways and applications to Watson IoT Platform,

      Watson IoT Node – A pair of nodes for connecting your device or gateway to the IBM Watson Internet of Things Platform. A device or gateway can use these nodes to send events and receive commands from the application.

      IBM IoT App Node – A pair of nodes for connecting your application to Watson IoT Platform. An application can use these nodes to receive device events and send commands back to the device.

      So in your case, it seems you want to connect the device to Watson IoT Platform, in which case use the Watson IoT Out node as shown in step4 – https://developer.ibm.com/recipes/tutorials/getting-started-with-watson-iot-platform-using-node-red/#r_step4.

      Also, note that in order to use the IBM IoT App out node, you need to generate the API key from the Watson IoT Platform. This will connect the Node-RED to Watson IoT Platform as an application instead of device. (An application can subscribe to events from multiple devices and send commands to control the devices). The Step 3 – https://developer.ibm.com/recipes/tutorials/getting-started-with-watson-iot-platform-using-node-red/#r_step3 of this recipe shows how you can generate the API key from the dashboard.

      Please let us know if you need any further clarification on this.

  3. We are trying to develop server application (Node.js) that will monitor the temperature and send Green, Red command to Raspberry Pi. We are referring your tutorial for this. We have all the credentials for registered device. After creating full flow till 6th step there is an error in debug console: Error: [BaseClient:disconnect] Client is not connected. IBM IoT input node gets disconnected when the IBM IoT output node gets connected & vise-versa. Please help us to get out of it……

  4. Also we are little bit confuse about application ID in step no 5. Help us ASAP.

    • YMDH_sathish_Palaniappan December 19, 2016

      Yeah, do not use the application Id. Its required only when you configure it for scalable deployment. Since its already given, Please use a different API Key configuration for the input & output node. I mean the API Key & Token would be same, but create 2 configurations.

  5. Hello , the attribute of my”ibmiot” are “input Type”、”Device Id”and”Name”,but not have “KPI Key”、“Authentication”、”Output Type” etc.How to solve it ?thanks!

Join The Discussion