Contents


Build a connected-car IoT app with Geospatial Analytics

Deploy and extend a connected-vehicle starter kit

Comments

Want to build an Internet of Things (IoT) application on IBM Cloud? It's not as difficult as you might think. Most IoT apps consist of three pieces: a connected thing, an application to view and manage the thing, and analytics to detect events triggered by the thing.

The Internet of Things Platform service on IBM Cloud makes it easy to connect a thing to applications and analytics services. To demonstrate how easy it is, I built an IoT starter kit for connected cars. The Connected Vehicle kit consists of three pieces:

  • A vehicle simulator (a Node.js app)
  • HTML5 applications to view and manage vehicles on a map
  • On IBM Cloud, the Geospatial Analytics service and Node-RED for analytics

This tutorial guides you through configuring and deploying the Connected Vehicle starter kit on IBM Cloud and building the analytics with the Geospatial Analytics service and Node-RED.

What you'll need to build your app

Overview of the Connected Vehicle starter kit

The Connected Vehicle application you will configure and deploy has three components:

  • Node.js vehicle simulator
  • HTML5 Map app
  • HTML5 Tester app

These three components use the IBM Watson Internet of Things Platform for real-time publish/subscribe messaging with the MQTT protocol. The simulated vehicles publish telemetry data frequently (two messages per second) and subscribe to a command topic whereby they accept commands (for example, "set speed to 60") from the tester application. The Map app subscribes to the vehicle telemetry topic to display position and status in real time. The Tester app enables you to publish control commands to the vehicles and notifications to the Map app.

This overview diagram shows the relationships among the application's components:

Overview diagram of the Connected Vehicle starter kit
Overview diagram of the Connected Vehicle starter kit
1

Create an Internet of Things Platform service instance on IBM Cloud

  1. Log in to your IBM Cloud account.
  2. In the IBM Cloud dashboard, click Create resource.
  3. In the IBM Cloud catalog, click Internet of Things from the categories, and select Internet of Things Platform.
  4. Choose a region, change the service name to a unique name, verify that the Lite plan is selected, and then click Create.
  5. Click the Launch button. If you were not redirected to the Internet of Things Platform page, in the dashboard, click the newly created service, and then click Launch.

    You are now in the Watson Internet of Things dashboard, where you can register devices, generate API keys for applications, view your usage, and invite others to the organization:

    Screenshot of the Watson IoT Platform dashboard
    Screenshot of the Watson IoT Platform dashboard
2

Configure the Watson IoT Platform organization

The Connected Vehicle application uses Watson IoT Platform for near-real-time messaging between simulated vehicles and the Map and Tester apps. To facilitate this communication, you must first register the devices and generate an API key for the applications.

With the vehicle simulator, you can model multiple vehicles from a single Node.js runtime instance. Watson IoT Platform treats each vehicle simulator as a device. You'll eventually run three vehicle simulators, so the first step is to register these simulators manually to obtain access credentials:

  1. In the Watson IoT Platform dashboard, from the Devices page, click Device Types > Add Device Type.
  2. In the name field, type vehicle, and then click Next, and then click Done.
  3. Click Register Devices.
  4. Verify that vehicle is selected for the device type, and then specify a device ID of any length that will be unique to this organization, and then click Next. Screenshot of the Add Device Identity screen
    Screenshot of the Add Device Identity screen
  5. Click Next through the remaining screens, and then click Done.
  6. Write down the credentials for your device. For example:
    org=o4ze1w
    type=vehicle
    id=ABC
    auth-method=token
    auth-token=5QK1rWHG9JhDw-rs+S
  7. Create two more devices (for example, DEF and GHI) following the previous steps. Write down the credentials for these other devices. You'll configure the starter kit with this information.
  8. In the Watson IoT Platform dashboard, click Apps in the sidebar.
  9. Click Generate API Key, and click Next. Choose Standard Application as the role, and click Next.
  10. Write down this information. The Map and Tester apps will use these credentials to connect to Watson IoT Platform.
  11. In the Watson IoT Platform dashboard, click Settings in the sidebar. Scroll down to Connection Security. For the purposes of this tutorial, change the Default Connection Security Level to TLS Optional. Screenshot of the Connection Security Settings
    Screenshot of the Connection Security Settings
3

Download, configure, and deploy the starter kit

The source code for the IoT starter kit is stored in the bboyd | iot-vehicle-geospatial-starter-kit project.

  1. Download the code for the starter kit from the bboyd | iot-vehicle-geospatial-starter-kit project.
  2. From the download button (which is directly above the list of files), select Download zip.
  3. Extract the ZIP file.
  4. In your local project, open the manifest.yml file. Pick a globally unique application name (for example, bryancboyd-trafficsim), and enter that name for the host and name fields. Set the number of instances to 3, and then save the file.
  5. Open the config/settings.js file. This file stores all device and API key configuration data. Make these updates:
    • For iot_deviceType, enter vehicle.
    • For iot_deviceOrg, enter your six-character organization ID (for example, wz2q83k).
    • For iot_deviceSet, enter the ID and tokens for the three devices you registered.
    • For iot_apiKey, enter the API key you created.
    • For iot_apiToken, enter the API key token.
    • Keep the default values for notifyTopic and inputTopic; these are configuration parameters used by the Geospatial Analytics service.
  6. Save your changes.
  7. From the root directory of your extracted application, type
    cf login.

    Follow the prompts, entering https://api.ng.bluemix.net for the API endpoint and your IBM Cloud email address and password as login credentials. If you have more than one IBM Cloud organization and space available, you will also have to choose these.

  8. To deploy the starter kit app to IBM Cloud, type
    cf push
  9. After your application deploys, run the Map app at http://app-name.mybluemix.net. You will see three simulated vehicles moving across the map. Click a vehicle to view its telemetry data:
    Screenshot of the running Map app
    Screenshot of the running Map app

    If you don't see any vehicles, make sure that you are connecting with http and nothttps. The link directly from your dashboard uses https.

  10. Each vehicle simulator can simulate multiple vehicles. The count is controlled by an IBM Cloud environment variable: VEHICLE_COUNT. Type cf set-env <app-name> VEHICLE_COUNT 15 to increase the total number of vehicles to 15. Then, type cf restate <app-name> to view the new number of vehicles.
4

Create and configure Geospatial Analytics

By using the IBM Cloud Geospatial Analytics service, you can track when each vehicle enters or leaves a defined geofence region. The Map app can interact with the service, enabling you to graphically create and delete geofences dynamically:

  1. In the IBM Cloud dashboard for your new application, click Create resource.
  2. In the IBM Cloud catalog, search for and select Geospatial Analytics .
  3. Choose the selected plan of Free and click Create. The service is not yet started. On the name of your Cloud Foundry app, click Connections > Connect to bind the service to your application. When prompted, restage the app.
  4. The starter-kit application includes APIs to start and stop Geospatial Analytics with the configured Watson IoT Platform organization and messaging credentials. To start the service, browse to http://app-name.mybluemix.net/GeospatialService_start and wait for the page to show success (which might take 30-45 seconds).
  5. Open the Map app and create some geofences. Click the Alert button (the exclamation-point icon) on the toolbar to start creating a geofence, and drag the handles and edges to position the geofence. To create the geofence you defined, click the center black circle to open the context menu, and then click Create.Screenshot of crating a geofence
    Screenshot of crating a geofence

The Geospatial Analytics service adds this geofence to the list of watched regions and publishes an MQTT message through Watson IoT Platform whenever a vehicle enters or leaves the area. The Map app consumes the message and displays an overlay over the vehicle on the map.

Screenshot of map with overlay
Screenshot of map with overlay

To delete a geofence, select the region and click Delete.

5

Use the Tester app

The Tester app sends commands to the simulated vehicles and the Map app. The vehicle simulator subscribes to commands of type setProperty and dynamically changes its own properties, speed, and state. The Map app subscribes to commands of type addOverlay and dynamically displays a pop-up of text over a vehicle.

  1. Open the Map app and Tester app (http://app-name.mybluemix.net/tester) side-by-side, so that you can see both pages.
  2. To configure the setProperty command, click on a vehicle and enter the ID in the bottom form on the Tester app. Enter a property of speed and a value of 100, and click Update Property. You will see the MQTT topic and payload containing the command in the Tester app, and the selected vehicle will change speed to 100 mph.

    Note: The vehicles simulate a set of static properties (location, speed, state, and type) and custom properties. You can use the setProperty API to dynamically add/change/delete a custom property on a vehicle. To add a property, publish a property that doesn't yet exist (for example, DriverWindow = UP). To delete a property, update the property with a value of an empty string; the vehicle will stop including the property in its telemetry message.

    Screenshot of the UI for configuring the setProperty command
    Screenshot of the UI for configuring the setProperty command
  3. To configure the addOverlay command, in the Tester app, use the upper form to display a message over a vehicle.Screenshot of the UI for configuring the addOverlay command
    Screenshot of the UI for configuring the addOverlay command
6

Create a Node-RED analytics application

You can use the Node-RED boilerplate in IBM Cloud to extend the starter kit with basic analytics. Node-RED is a visual tool for wiring together events in IoT use cases. With Node-RED, you can design flows of logic that link a variety of inputs (such as MQTT, TCP, and HTTP) to outputs (such as MQTT, HTTP, Twitter, MongoDB, and Cloudant) to add lightweight analytics quickly.

  1. Deploy the Node-RED boilerplate application in IBM Cloud. In your IBM Cloud dashboard, click Create resource.
  2. Search for and choose the Node-RED Starter boilerplate. Provide a unique name and host name (for example, bryancboyd-nodered), and click Create.
  3. On the Getting started page, click Connections. (Or, on your IBM Cloud dashboard, click the name of the Node-RED application, then click Connections.) Click Create connection, and choose the Internet of Things Platform service that you created in Step 1. When prompted, restage the app (or manually restart the app).
  4. After the application restages, open the Node-RED canvas at http://node-red-app.mybluemix.net/.
  5. Click Next. Create a user name and password to secure your Node-RED editor, and then click Next through the screens, and finally click Finish.
  6. Build a flow to monitor telemetry for all vehicles.
    1. Drag an ibmiot input node from the palette on the left onto the canvas.
    2. Drag a debug node to the right of the ibmiot node and wire the two nodes together.
    3. Double-click the ibmiot node and configure it as follows:
      • For Authentication, select Bluemix Service.
      • For Input Type, select Device Event.
      • For Device Type, enter vehicle.
      • For Device Id, select the All check box.
      • For Event, enter telemetry.
      • For Format, enter json.
      • For Name, enter telemetry.
      • For QoS, enter 0.

      Make sure that these fields have these values without a + sign in front of them.

    Screenshot of configuring a Node-RED node
    Screenshot of configuring a Node-RED node
  7. Click Done.
  8. Click Deploy (top-right corner of page).
  9. Select the debug pane. If configuration was successful and the starter kit application is currently running, you will see the MQTT payloads for the connected vehicles in the debug pane. Screenshot of configuring a Node-RED node
    Screenshot of configuring a Node-RED node
  10. If your VEHICLE_COUNT environment variable is set to a value greater than 1, the telemetry data for VEHICLE_COUNT vehicles is contained in a single array.

    To modify the flow to filter for a single vehicle (for example, ABC-2), add a function node in the middle of your flow, double-click it, and fill in the following code:

    var data = msg.payload;
    for (var i in data) { 
      if (data[i].id == "ABC-2") { 
        msg.payload = data[i]; 
           return msg;
      }
    }

    Wire the flow together, and then click Deploy. You should now see data for a single vehicle in your debug pane.

    Screenshot of data for a single vehicle in the debug pane
    Screenshot of data for a single vehicle in the debug pane
7

Create a virtual key fob in Node-RED

Next, use Node-RED to build a simple remote control to lock and unlock a vehicle. You will use two inject nodes — one to unlock the vehicle and the other to lock it. For each operation, you'll publish a setProperty command for the lockState property with a value of locked or unlocked, then publish an addOverlay command to display a notification on the Map app.

  1. Go to your Node-RED flow, and drag two inject input nodes onto the Node-RED canvas. Edit each node and configure a string payload: locked for one, unlocked for the other. This payload will be the value that is sent in the setProperty command.Screenshot of configuring a string payload
    Screenshot of configuring a string payload
  2. Add a function node to the flow and wire both inject nodes to it. This function will build and publish two commands to Watson IoT Platform — one for setting the vehicle state and the other for displaying an overlay message on the Map app.

    Use the following code:

    var commandValue = msg.payload;
    var setPropertyMsg = {
            deviceId: "ABC",
            deviceType: "vehicle",
            eventOrCommandType: "setProperty",
            format: "json",
            payload: JSON.stringify({
                   "id": "ABC-2",
                   "property": "lockState",
                   "value": commandValue
            })
    }
    var addOverlayMsg = {
            deviceId: "tester",
            deviceType: "api",
            eventOrCommandType: "addOverlay",
            format: "json",
            payload: JSON.stringify({
                   "id": "ABC-2",
                   "text": commandValue,
                   "duration": 5000
            })
    }
    return [ [setPropertyMsg, addOverlayMsg] ];
  3. Add an ibmiot output node to the flow, after the function node. The function node will overwrite many of the configuration values on the ibmiot node; these fields we will mark with a "dummy" value of override. Double-click the ibmiot node and configure it as follows:
    • For Authentication, select Bluemix Service.
    • For Input Type, select Device Command.
    • For Device Type, enter override.
    • For Device Id, enter override.
    • For Command Type, enter override.
    • For Format, enter json.
    • For Data, enter override.
    • For Name, enter commands.

    Make sure that when you switch the output type to Device Command that the Event Type label becomes Command Type; otherwise, you might receive 502 errors.

    Screenshot of configuring a node with dummy values
    Screenshot of configuring a node with dummy values
  4. Deploy the application (click Deploy in the top-right corner of the page), and click the button on the inject nodes while watching the Map app. You can see the lockState property update for vehicle ABC-2, and an "unlocked" message appears on the map. Screenshot of the unlocked message appearing on the map
    Screenshot of the unlocked message appearing on the map
8

Tweet geospatial events with Node-RED

With the IBM Cloud Geospatial Analytics service, you can create geofence polygons in the Map app and receive Watson IoT Platform events when a vehicle enters or leaves a region. The Map app already subscribes to this event topic and displays messages as a notification overlay over the vehicle. This geospatial event topic can be subscribed to by multiple applications, and it can be a building block used to create more-complex scenarios — for example, a bounding box for young drivers, signaling parents whenever their child drives outside of an "approved" zone. Or, detect when your vehicle has entered a geofence surrounding your house and notify your house automation system to prepare for your arrival.

You can use Node-RED to link geofence alerts to other applications and APIs. In this flow, you'll publish a tweet when receiving a geofence notification message for a particular vehicle:

  1. Drop an ibmiot input node onto the canvas. Double-click the ibmiot node and configure it as follows:
    • For Authentication, select Bluemix Service.
    • For Input Type, select Device Command.
    • For Device Type, enter api.
    • For Device Id, enter geospatial.
    • For Command Type, enter geoAlert.
    • For Format, enter json.
    • For Name, enter commands.
    Screenshot of the ibmiot node configuration UI
    Screenshot of the ibmiot node configuration UI
  2. Add a function node after the ibmiot input node. This function will filter the data returned from the geospatial service and continue flow execution only if the vehicle for the alert matches an ID specified. Use the following code (if desired, replace the ID with a vehicle in your environment).
    msg.payload = {
       time: msg.payload.time,
       id: msg.payload.deviceInfo.id,
       lon: msg.payload.deviceInfo.location.longitude,
       lat: msg.payload.deviceInfo.location.latitude,
       eventType: msg.payload.eventType
       region: msg.payload.regionId 
           } 
           if (msg.payload.id == "ABC-3") { return msg; }
  3. Wire the function node to a debug node, and deploy the app again.
  4. Drag a twitter output node onto the canvas, and wire the output of the function to the input of this node. You can use the twitter node to configure an existing Twitter account using OAuth, and then tweet the contents of msg.payload. Sign in to your Twitter account and modify the function node to build the message for Twitter.
    msg.payload = {
       time: msg.payload.time,
       id: msg.payload.deviceInfo.id,
       lon: msg.payload.deviceInfo.location.longitude,
       lat: msg.payload.deviceInfo.location.latitude,
       eventType: msg.payload.eventType,
       region: msg.payload.regionId 
           } 
           if (msg.payload.id == "ABC-3") { 
        var verb = "exited";
        if (msg.payload.eventType == "Entry") { verb = "entered"; }
        msg.payload = "Vehicle " + msg.payload.id + " has " + verb + 
           " region " + msg.payload.region + "!";
        return msg; 
           }
  5. Deploy the application.

    Now Node-RED will publish a tweet whenever a geofence is crossed by your vehicle.

    Screenshot of tweet published by Node-RED
    Screenshot of tweet published by Node-RED
9

Use the Watson IoT Platform dashboard to analyze your connected cars

To review and gain insight into your vehicles (such as their headings and their latitude and longitude), you can create a board and card on your Watson IoT Platform dashboard.

  1. On your Watson IoT Platform dashboard, click Boards, then click Create New Board.
  2. Give the board a name, and then click Next and Submit.
  3. Click on your newly created board, then click Add New Card.
  4. Click on Device Properties, and then select one of the Device IDs and click Next.
  5. Click Connect new data set, and then select the telemetry event, and the lat property. Connect a new data set and telemetry event for the lng and heading properties.
  6. Select your size, then click Next and Submit.

Each card on the board can be customized.

Conclusion

Building an IoT application with the Watson Internet of Things Platform and Geospatial Analytics services in IBM Cloud is simple and easy. Try it for yourself! Extend the Connected Vehicle Starter Kit with other IBM Cloud services, mobile applications, or even physical sensors.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Internet of Things, Cloud computing
ArticleID=998321
ArticleTitle=Build a connected-car IoT app with Geospatial Analytics
publish-date=03192018