Taxonomy Icon

IoT

The Internet of Things, or IoT, refers to the growing range of Internet-connected devices that capture or generate an enormous amount of information every day. For consumers, these devices include mobile phones, sports wearables, home heating and air conditioning systems, and more. In an industrial setting, these devices and sensors can be found in manufacturing equipment, the supply chain, and in-vehicle components. IoT can make life easier for all of us. To easily develop and deploy IoT solutions of all sizes, IBM created the IBM Watson IoT Platform.

In this tutorial, you will learn how you can use the Watson IoT Platform to build a simple IoT solution by turning your smartphone into a sensor (reading and sending data) but also into an actuator (reading and acting on data).

You’ll use an IoT Starter Mobile app on your smartphone. To transform your smartphone into a sensor, we will build an IoT app that reads the accelerometerThe accelerometer is a built-in electronic component that measures tilt and motion. It can also detect rotation and motion gestures, such as swinging or shaking. values that are sent from your smartphone and reacts with a specific action whether the values reach a certain threshold. To transform your smartphone into an actuator, we will build an IoT app that sends specific commands to your smartphone that can then react to the commands it receives.

What you’ll need to build these IoT apps

You’ll need the following devices or accounts:

  • An IBM Cloud account.
  • A smartphone (an Android or iOS smartphone).
  • For an iOS smartphone, a valid iOS Developer License and Apple Xcode.
  • A twitter account to be notified by a tweet (optional).
  • An email account with SMTP relay capabilities to be notified by an email message (optional).

Before you begin, review the following information:

  • Familiarity with IBM Cloud Platform. You need to know how to browse the catalog and instantiate one of the services. (You can complete the IBM Cloud Essentials course to gain a complete understanding of IBM Cloud.)
  • Familiarity with Node-RED. You need to understand how to use nodes in Node-RED and how you process a message in Node-RED. Node-RED is a front end to JavaScript, so you also need some experience with JavaScript. You can use the getting started documentation on the Node-RED website to help you gain this familiarity.
  • Review the Getting Started with Watson IoT Platform IBM Cloud documentation.

Architecture of our IoT apps

The high-level view of the architecture for our IoT solution is shown in the following figure:

In this tutorial, you will create an IoT app in the IBM Cloud that will manage two other IoT applications:

  • An IoT sensor app that reads and receives accelerometer values from your smartphone. This app manages the use case of when your smartphone is falling down or moving too fast. If its acceleration exceeds a certain threshold limit, you will be alerted.
  • An IoT actuator app that sends simple commands to your smartphone. We will use the IoT Starter Mobile app, which provides the list of simple commands that your smartphone can interpret. For instance, based on the position of your smartphone, we will turn on or off the light or change the background color of your smartphone.
1

Create your main IoT app in the IBM Cloud

Our main IoT app in IBM Cloud will be our backend application in our IoT solution. Our backend application will read, receive, and interpret incoming payload messages that contain sensor data. Additionally, it will define and send IoT commands to actuators based on certain conditions being met.

  1. Log in to your IBM Cloud account.
  2. In the IBM Cloud catalog, from the Boilerplates section, select the Internet of Things Platform Starter boilerplate.
  3. In the right pane, specify a unique name for your app, which is used to create a unique host name for your app. Then, click Create.

The Internet of Things Platform Starter boilerplate automatically adds the Internet of Things Platform service and a Cloudant NoSQL Database service to your app. It also includes a Node-RED runtime environment for your app.

2

Register your smartphone in the Watson IoT Platform

You need to register your smartphone in the Watson IoT Platform before you can connect it to the IoT. The Watson IoT Platform service automatically allocates an IoT organization to you. An IoT organization is a space that is used for connecting and managing devices to the Watson IoT Platform so that your applications can access their live and historical data.

  1. From your IBM Cloud Dashboard, select the Internet of Things Platform service. Then, click Launch.
    The dashboard for IBM Watson IoT Platform opens in a new browser tab. The organization ID is assigned to your app and is displayed in the upper right.
  2. In the Boards page, which is where you manage your devices and data, hover over the menu on the left and select Devices. On the Devices page, click Add Device.
  3. In the Add Device page, click Create device type. The name for the device type is case-sensitive and must be either Android or iPhone. The IoT Starter Mobile app expects one of these words as the device type.

That’s it! Your smartphone has been registered with Watson IoT Platform. You still need to connect it to the Watson IoT Platform, but before you can do that, you need to install and configure the IoT Starter Mobile app on your smartphone.

3

Install and configure the IoT Starter Mobile app on your smartphone

You will use the IoT Starter Mobile app to both read and send sensor data that comes from your smartphone and also to transform your smartphone to be an actuator that can receive and run commands. This application has been developed with native languages on both iOS and Android platforms. With this mobile app, you can publish the following events:

  • Accelerometer X, Y, Z event of your smartphone
  • touchMove event
  • Text event
3a

Install the IoT Starter Mobile app on your iOS smartphone

You need to download, build, and install the IoT Starter Mobile app.

  1. Download the IoT Starter Mobile app for iOS demo application from the iot-starter-for-ios GitHub project.
  2. Import it into your Xcode development environment.
  3. Build the .ipa package file. For iOS 10, to build the .ipa file for your starter app, you need to add the “Privacy – Camera usage description” key to your app’s Info.plist.
  4. Deploy the .ipa package file on to your iOS smartphone.
  5. After the demo app is installed on your smartphone, open the IoT Starter Mobile app. Its icon looks like this icon:

Depending on the version of the iOS on your smartphone, you might be prompted to trust the International Business Machines developer. In the General Settings for your iOS smartphone, scroll down and select Device Management. Select International Business Machines, and then click the Trust “International Business Machines” link. You’ll see IoT Starter in the list of apps, and it’ll be listed as verified.

3b

Install the IoT Starter Mobile app on your Android smartphone

You need to download, build, and install the IoT Starter Mobile app.

  1. Download the IoT Starter Mobile app for Android demo application from the iot-starter-for-android GitHub project.
  2. Import it into your Android development environment.
  3. Build the .apk package file.
  4. Deploy the .apk package file on to your Android smartphone.
  5. After the demo app is installed on your smartphone, open the IoT Starter Mobile app. Its icon looks like this icon:

4

Verify that smartphone messages are being sent to the Watson IoT Platform

After you install the IoT Starter Mobile app on your smartphone, you need to configure it with your IoT credentials and connect the app to the Watson IoT Platform.

  1. Open the IoT Starter app on your smartphone, and specify your organization and smartphone credentials.
  2. Open the profile for the app.

    For Android devices, select the menu in the upper right, and select Open profiles.

    For iPhone devices, select the Pr…iles link, and select Open profiles.

  3. Click Save setting and give a name to your profile, such as myProfile. Click Save, and go back to the login window. Your credentials are now saved for the next time you connect.

  4. Click Activate Sensor, which causes your app to send messages to the Watson IoT platform.
  5. In the Watson IoT Platform dashboard (in IBM Cloud), in the menu on the left, select Devices. Select your smartphone in the list. Verify that accelerometer events are displayed in the Recent Events section.
  6. If you like, you can add a card to your dashboard to visualize your smartphone data (in real time even). Use the Watson IoT Platform documentation on IBM Cloud to learn how to create boards and cards.
5

Process messages from your IoT sensor app

Now that your smartphone is registered, and you verified that it is sending its accelerometer data to the Watson IoT Platform, we need to connect the IoT app to the Watson IoT platform by using the IoT service. We can then start to use that smartphone data in our IoT solution.

  1. In the IBM Cloud dashboard, go to your application and click your application route to access your application.
  2. Open your Node-RED flow editor.
  3. In the Node-RED editor, which opens and contains a sample flow, select all existing nodes and delete them.
  4. Create a new flow by dragging an ibmiot node from the input section on to your workspace and also dragging a debug node from the output section on to your workspace. Connect the two nodes together.
  5. Double-click the IBM IoT node to configure it. Specify the IBM Cloud service authentication and device ID information, which is the one you choose when you registered the smartphone with the Watson IoT Platform. Then, click Done.
  6. Click the Deploy button in the upper right of the Node-RED flow editor.
    The button turns gray when the flow is deployed.
  7. Select the debug tab to see your sensor data from your smartphone.
    If you cannot see the debug tab, you might need to extend your browser window (or scroll) to see it.

Your sensor data is received in JSON format. The IoT Starter Mobile app uses the MQTT protocol to send the data.

6

Send an alert when your smartphone falls down

Now, we are going to update our Node-RED flow to use the sensor data.

We are going to do the following steps:

  • Extract the “acceleration_y” value from the JSON payload message
  • Trigger a value against an acceleration value (such as 0.5 for iOS and 7 for Android)
  • Debug the notification message
  • Optionally, either post a tweet or send an email

Go to your Node Red flow editor. You will create the following flow by dragging the appropriate nodes and wiring them together as shown in the following figure:

  1. To extract the absolute acceleration_y value of the smartphone from the JSON payload message, we’ll add and configure a function node. From the function section of the palette, drag a function node to your workspace. Double-click the function node to configure it with these values:

    1. Specify getAcceleration_y as the name for this node.
    2. In this function node, copy and paste the following code: return {payload: Math.abs(msg.payload.d.acceleration_y)};
    3. Click Done.
  2. To create a trigger on the acceleration_y value, we’ll add and configure a switch node. From the function section of the palette, drag a switch node to your workspace. Wire the function node to the switch node. Double-click the switch node to configure it with these values:

    1. Specify testAcceleration_y as the name for this node.
    2. Specify msg.payload as the property.
    3. In the condition value drop-down list, select “>=?”, and specify 0.5 for iOS or 7 for Android.
    4. In the last drop-down list, select stopping after first match.
    5. Click Done.
  3. To define the notification message that you want to send when your phone is falling, we’ll add and configure a template node. From the function section of the palette, drag a template node to your workspace. Wire the switch node to the template node. Double-click the template node to configure it with these values:

    1. Specify Acceleration_y_exceed_message as the name for this node.
    2. Specify msg.payload as the property.
    3. Copy and paste the following code to the node editor:
      Wow! Is your phone falling?
      Its acceleration y = {{payload}}!Wow! Is your phone falling? Its acceleration y = {{payload}}!
    4. Click Done.
  4. To limit the number of messages for the notification and to avoid duplicate notification messages, we’ll add and configure a delay node. From the function section of the palette, drag a delay node to your workspace. Wire the template node to the delay node. Double-click the delay node to configure it with these values:

    1. Specify Limit Rate as the name for this node.
    2. From the Action drop-down list, specify Limit rate to. Then, set the rate to 1 and select Minute.
    3. Check the Drop intermediate message check box.
    4. Click Done.
  5. To display the notification message in the Debug tab of your flow, we’ll add and configure a debug node. From the output section of the palette, drag a debug node to your workspace. Wire the delay node to the debug node.

  6. To avoid getting too many debug messages in the Debug tab, you can activate and deactivate the debug node by clicking the green rectangle in the debug node.

    A message is displayed at the top of your browser that explains if the debug node is activated or deactivated.
  7. To test your IBM Cloud application (and your Node-RED flow), complete these steps:

    1. Click Deploy to redeploy your Node-RED flow.
    2. On your smartphone, run the IoT Mobile Starter app, and click Activate Sensor.
    3. Move your smartphone quickly up and down to simulate it falling down.
    4. In your Node-RED flow editor, in the Debug tab, verify that acceleration_y values are being displayed and that the notification message is also displayed.
6a

Get notified by a tweet

If you have a Twitter account, you can send your notification as a tweet.

  1. In your Node-RED editor, from the social section of the palette, drag a twitter out node to your workspace. Wire the twitter out node to the delay node output.

  2. Double-click the twitter out node to configure it with these values:

    1. In the twitter out dialog box, select the pencil icon next to the Twitter ID drop-down list.
    2. In the next dialog box, click the button to authenticate with Twitter. In the window that is displayed, specify your Twitter credentials and authorize your IBM Cloud app to use your Twitter account.
    3. Click Add to add that Twitter account.
    4. In the twitter out dialog box, make sure that your ID is selected.
  3. Click Deploy to test this new version of your flow. If your Deploy button is red, it means that your flow has been updated and needs to be redeployed. If your Deploy button is gray, it means that your flow is deployed.

  4. To test this notification method, complete these steps:

    1. On your smartphone, make sure the IoT Starter app is running, and click Activate Sensor, if necessary.
    2. Move your smartphone quickly up and down to simulate it falling down.
    3. In the Debug tab, verify that you see the acceleration values and notification message.
    4. Access your Twitter app and verify that you see the tweet with your notification message from your IBM Cloud app.
6b

Get notified by an email

If you have an SMTP email account, you can have the app send an email with the notification that your smartphone is falling. You might need to configure security settings for your email to allow your app to send email. For example, if you are using a Gmail account, you must enable the Allow less secure apps option in the Sign-in & security settings.

  1. In your Node-RED editor, from the social section of the palette, drag an e-mail out node to your workspace. Wire the e-mail out node to the delay node output.

  2. Double-click the e-mail out node to configure it with these values:

    1. In the To field, specify your email address.
    2. In the Server field, specify your SMTP server address, such as smtp.gmail.com.
    3. In the Port field, specify the SMTP TCP port that sends email, such as 465.
    4. In the Userid field, specify the user name to use to authenticate with the SMTP server. This user name might be your email address.
    5. In the Password field, specify the password that is associated with your user name.
  3. To test this notification method, complete these steps:

    1. On your smartphone, make sure the IoT Starter Mobile app is running, and click Activate Sensor, if necessary.
    2. Move your smartphone quickly up and down to simulate it falling down.
    3. In the Debug tab, verify that you see the acceleration values and notification message.
    4. Access your mail app and verify that you see the email with your notification message from your IBM Cloud app.
7

Send a command to your smartphone

Until now, your smartphone has been acting as a sensor. However, you can use the IoT Starter Mobile app to turn your smartphone into an actuator by having your smartphone receive and act on commands.

The IoT Starter Mobile app can manage three types of events:

  • accel events, for the accelerometer
  • touchmove events, for the swipe event on your smartphone
  • text events, for text commands

The app can receive and act on four commands:

  • light – This command turns on or off the light on your smartphone.
  • color – This command changes the background color of the IoT Starter Mobile app.
  • alert – This command displays an alert message in the app.
  • any text value – This command logs a message in the app.
7a

Create the IoT Actuator app in Node-RED

  1. Download the /flows/commands.json file from my watson-iot-actuator GitHub project to your computer.
  2. Open the commands.json file in a text editor, and make sure that all the code is on a single line. Remove any line breaks, if necessary. Copy the line of code.
  3. In your Node-RED editor, create a new flow to your workspace by clicking the plus icon.
  4. Press Ctrl+I to open the Import Nodes dialog box. Paste the line of code, and click Import. The following flow is displayed in your workspace:

  5. To customize this flow for your IoT Actuator app, you need to configure the nodes as described below:

    1. Double-click the IoT App In node, and specify the smartphone ID that you used when you registered your smartphone. Click Done.
    2. Double-click the IoT App Out node, and specify the smartphone ID, smartphone type (either iPhone or Android). Click Done.
  6. Click Deploy.

7b

Test the commands on your smartphone

  1. On your smartphone, make sure that the IoT Starter Mobile app is running, and click Activate Sensor, if necessary.
  2. Move your smartphone around; flip it and tilt it. The background color of the app on your phone changes colors. Your smartphone is receiving the accel event.
  3. On your mobile smartphone with the IoT Starter Mobile app in the foreground, swipe left and right with one finger on the screen. Check the Log tab in your app. Two messages are logged. Your smartphone is receiving the touchmove event.

  4. On your smartphone, go back to the IoT tab. Click the Send Text button. Type any text value, and click the Submit button.

  5. Again, check the Log tab to see that the two messages were logged. Your smartphone is receiving the text event.

  6. On your smartphone, go back to the IoT tab. Click the Send Text button. Type alert in the field, and click the Submit button. A pop-up box displays an alert. Your smartphone is receiving the alert event.

  7. On your smartphone, go back to the IoT tab. Click the Send Text button. Type light in the field, and click the Submit button. The light on your smartphone is turned on; this command might not work on all Android smartphones, but it works on all iOS smartphones. Your smartphone is receiving the light event. You can click Send Text again, type light, and the light will be turned off.

In the next step, we will create an IoT app that combines the idea of your smartphone being both a sensor and an actuator.

8

Turn on and off the light of your smartphone when you flip it horizontally

Now that you see how to turn your smartphone into a sensor or an actuator, let’s create an IoT app that turns your smartphone into both! In this scenario, we will turn the light of your smartphone on or off each time you flip it horizontally.

We will test the value of the acceleration Z from the smartphone to check whether this value is positive or negative and save the state.

  • If acceleration Z is positive, then if the light is turned off, send a light command to the phone to turn the light on.
  • If acceleration Z is negative, then if the light is already turned on, send a light command to the phone to turn the light off.

  • Go to your Node Red flow Editor. You will create the following flow by dragging the appropriate nodes and wired them as shown below:

  • From the function section of the palette, drag a function node to your workspace.

    1. Specify a name for this function node. For example, name it Detect Flip.

    2. Cut and paste the following code in the function node editor:

      
      var accelerationZ = msg.payload.d.acceleration_z;
      var isAlreadySwitchedOn = context.get('isAlreadySwitchedOn')|| false;
      
      // For Android reverse this test !!!
      if (accelerationZ > 0) {    
          if (!isAlreadySwitchedOn) {
              isAlreadySwitchedOn = true;
              msg.eventOrCommandType = "light";
              msg.payload = JSON.stringify({"d":{"text":"Received light on message"}}); 
          }
      } else {
          if (isAlreadySwitchedOn) {
              isAlreadySwitchedOn = false;
              msg.eventOrCommandType = "light";
              msg.payload = JSON.stringify({"d":{"text":"Received light off message"}}); 
          } 
      }
      context.set('isAlreadySwitchedOn', isAlreadySwitchedOn);
      return msg;
      
      
      

    3. Click Done.

  • Drag a switch node to your workspace. This node will test whether we need to send a command to the phone. Fill in the fields with these values:

    1. Specify a name for this switch node. For example, name it Flip Detected.
    2. Set the Property to msg.eventOrCommandType.
    3. Select is not null in the drop-down list.
    4. Select stopping after first match in the bottom drop-down list.
    5. Click Done.
  • Drag an ibmiot out node to your workspace. This node will send the light command to the phone. Fill in the fields with these values:

    a. Specify a name for this node. For example, name it IBM IoT Out. b. Select IBM Cloud Service in the Authentication drop-down list. c. Select Smartphone Command in the Output Type drop-down list. d. Enter your smartphone type (iPhone or Android). e. Enter your smartphone ID. f. Enter text in the Command Type text box. g. Specify json in the Format text box. h. In the Data box, type this string:
    {"d":{"value":"text"}} i. Click Done.

  • Deploy your new flow. Grab your phone and run the IoT Starter Mobile app by clicking Activate Sensor.

    a. Watch the Debug tab in your Node-Red flow to see the incoming MQTT messages from the phone. b. Flip your phone horizontally and check that the light is ON. c. Flip it back, and check that the light is OFF.

If your Android smartphone does not interpret the light command well, you can replace the code in the function node with the following code. It provides an alternative solution that uses the color command that will change the background color of the IoT Starter Mobile app each time you flip it horizontally instead of turning on or off the light of your smartphone.


var accelerationZ = msg.payload.d.acceleration_z; 
var r = 0.0; 
var b = 0.0; 
var g = 0.0; 
a = 1.0; 

 
if (accelerationZ < 0) { 
    // green 
    r = 102.0; 
    g = 255.0; 
    b = 102.0; 
} else { 
   // purple 
    r = 178.0; 
    g = 102.0; 
    b = 255.0; 
} 
msg.eventOrCommandType = "color"; 
msg.payload = JSON.stringify({"d":{"r":r,"b":b,"g":g,"alpha":a}}); 
return msg; 

Conclusion

In this tutorial, you learned how to easily create and deploy IoT apps, how to easily turn your smartphone into a sensor and an actuator device, how to easily connect it to the IBM Watson IoT Platform, and how to send and receive data from your smartphone.

By using the IBM Cloud Platform and the Watson IoT Platform, you can accelerate your development time and your time to market. Organizations can quickly connect their devices (their own set of sensors or actuators, or both), build IoT apps, solve specific business problems, and transform their companies and industries.