AL4: IBM Internet of Things Foundation Lab Instructions

IBM WebSphere Technical University
Oct 28 to Oct 31, Düsseldorf
AL4: IBM Internet of Things
Foundation
Lab Instructions
Author:
Bryan Boyd, [email protected]
Page 1 of 31
IBM WebSphere Technical University
1 Introduction
This lab provides hands-on experience with IBM Internet of Things Foundation (IoT
Foundation), a cloud service allowing you to easily connect IoT devices and
applications together. You will deploy a provided Connected Vehicle simulator to IBM
Bluemix, then configure an Internet of Things service to capture this data and share
with a visualization tool.
In this
•
•
•
•
•
1.1
lab, you will:
Create (if necessary) an IBM Bluemix account
Create an Internet of Things service in Bluemix
Download and configure the Connected Vehicle application
Deploy the Connected Vehicle application to Bluemix
Bind a Geospatial Analytics service in Bluemix
System information
Username: virtuser
Password: impact2014
1.2
Connected Vehicle application
The Connected Vehicle application you will configure and deploy in this lab has three
separate components:
1) Node.js vehicle simulator
2) HTML5 Map app
3) HTML5 Tester app
The three applications use IBM IoT Foundation for real-time publish/subscribe
messaging, using the MQTT protocol. The simulated devices (vehicles) publish
telemetry data frequently (5 msgs/sec) and subscribe to a command topic whereby
they accept commands from the tester application (ex. set speed to 60). The Map
app subscribes to the vehicle telemetry topic in order to display position and status
in real-time. The Tester app allows you to publish control commands to the vehicles
and notifications to the Map app.
Page 2 of 31
IBM WebSphere Technical University
Messaging in the Connected Vehicle application
2 Create a Bluemix account
If you do not already have an IBM Bluemix account, visit http://www.bluemix.net to
sign up for an account. The basic account is free for 30 days, and provides enough
compute resources to run this lab. Once the account request is submitted, you will
receive a confirmation email within 1-2 minutes.
NOTE: Make sure to use an email address that you will be able to access from the
lab image or from your personal computer.
3 Create an Internet of Things service
From your Bluemix dashboard, select Add a Service.
Page 3 of 31
IBM WebSphere Technical University
Choose Internet of Things from the service list.
Provide a service name that you will recognize later (ex. iot-trafficsim) — this service
represents an organization in IoT Foundation, which is a shared space where
devices and applications can securely connect and share data. The service name you
enter here is just for your reference, you will not collide with other users with the
name iot-trafficsim. Press Create to add the service.
Page 4 of 31
IBM WebSphere Technical University
The Selected Plan of Free will allow you to register a maximum of 20 devices at no
charge. For other pricing details, visit the Internet of Things Foundation website:
http://internetofthings.ibmcloud.com
After the service is loaded, you will see the service information page with instructions
and documentation for registering devices. To view your newly-create Internet of
Things dashboard click the Launch button in the top-right corner of the page.
You will be redirected out of Bluemix to the Internet of Things Foundation website.
Page 5 of 31
IBM WebSphere Technical University
From this dashboard, you will be able to manually register devices, generate API
keys for applications, and invite other people to your organization.
4 Configure the IoT Foundation organization
The Connected Vehicle application uses IoT Foundation for near real-time messaging
between simulated vehicles (our devices) and the Map and Tester apps
(applications). To facilitate this communication, you first have to register the devices
and generate an API key for the applications.
4.1
Register devices
The vehicle simulator allows you to model multiple vehicles from a single Node.js
runtime instance. Each vehicle simulator will be treated as a device by IoT
Foundation. You will eventually run 3 vehicle simulators, so the first step is to
manually register these simulators to obtain access credentials.
From the organization dashboard's Devices tab, select Add Device. In the Device
Type dropdown, select Create a device type... and enter vehicle in the field
below. Choose a device ID of any length that will be unique to this organization (ex.
ABC, DEF, GHI) and select Continue.
Page 6 of 31
IBM WebSphere Technical University
The next screen show you the credentials for your device. For example:
org=o4ze1w type=vehicle id=ABC auth-­‐method=token auth-­‐token=5QK1rWHG9JhDw-­‐rs+S Save this information in a file as you will need these crednetials later. Now create
two more devices and also save the credentials. Note that when creating the first
device, create a type of vehicle, so you can select that from the Device Type
dropdown when creating subsequent devices. For example, the other two device
credentials may be:
org=o4ze1w type=vehicle id=DEF auth-­‐method=token auth-­‐token=Q7QmQ*!jQn6NUF&rA4 org=o4ze1w type=vehicle id=GHI auth-­‐method=token auth-­‐token=4O_FET9iLe(4bK!))z Page 7 of 31
IBM WebSphere Technical University
4.2
Generate an API key
You next will generate an API key for your organization. An API key provides
credentials for any application (i.e. not a device) to connect to IoT Foundation using
an MQTT client.
From your organization dashboard, click on the API Keys tab and select New API
Key.
Copy down the key and token, for example:
Key: a-­‐o4ze1w-­‐b7xr3coycy Auth Token: d4QD9Y@LcbrshlCD7q Again, save the key and token in a file as you will need them later.
On the API Keys tab, you will see a new table row for the key you just created. Add
a comment to the key to associate this with the Connected Vehicle application.
Page 8 of 31
IBM WebSphere Technical University
5 Download and configure the Connected Vehicle
application
Download the Connected Vehicle application to your local machine:
http://m2m.demos.ibm.com/trafficsimulator-WTU.zip
Unzip the file to C:\Users\virtuser\trafficsimulator
Navigate to C:\Users\virtuser\trafficsimulator\ in Windows Explorer, then right-click
on manifest.yml and select Edit with Notepad++
Page 9 of 31
IBM WebSphere Technical University
Now you must decide on a globally unique application name, which will be used when
deploying to Bluemix. For example: bryancboyd-trafficsim
Enter this application name for the host and name fields in manifest.yml
Set the number of instances to 3, then save the file.
Next, edit C:\Users\virtuser\trafficsimulator\public\config\settings.js
This file is shared by the Node.js vehicle simulator and the Map and Tester apps, and
stores all device and API key configuration data.
•
•
•
•
•
•
For iot_deviceType, enter vehicle
For iot_deviceOrg, enter your 6-character organization ID (ex: o4ze1w)
For iot_deviceSet, enter the three device ID and tokens 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 Bluemix Geospatial service
Page 10 of 31
IBM WebSphere Technical University
For example:
var config = { iot_deviceType: "vehicle", iot_deviceOrg: "o4ze1w", iot_deviceSet: [ { deviceId: "ABC", token: "5QK1rWHG9JhDw-­‐rs+S" }, { deviceId: "DEF", token: "Q7QmQ*!jQn6NUF&rA4" }, { deviceId: "GHI", token: "4O_FET9iLe(4bK!))z" } ], iot_apiKey: "a-­‐o4ze1w-­‐b7xr3coycy", iot_apiToken: "d4QD9Y@LcbrshlCD7q", // these topics will be used by Geospatial Analytics notifyTopic: "iot-­‐2/type/api/id/geospatial/cmd/geoAlert/fmt/json", inputTopic: "iot-­‐2/type/vehicle/id/+/evt/telemetry/fmt/json", }; Save your changes.
6 Deploy the application to Bluemix
To deploy the Connected Vehicle application to Bluemix, we will use the Cloud
Foundry command line tools.
6.1
Download the Cloud Foundry CLI
First, download and run the Cloud Foundry CLI tools installer:
https://cli.run.pivotal.io/stable?release=windows64&source=github
Complete the installation, following the prompts and choosing all default options.
6.2
Push the application to Bluemix
Open the Command Prompt, and type the following:
cd C:\Users\virtuser\trafficsimulator cf login Follow the prompts, entering https://api.ng.bluemix.net for the API endpoint, and
your Bluemix IBM ID email and password as login credentials. If you have more
than one Bluemix organization and space available, you will also have to choose
these.
For example:
Page 11 of 31
IBM WebSphere Technical University
Next, enter a cf push command to deploy your application to Bluemix. A Bluemix
application name matching your entry in manifest.yml will be created. If the
application deploys successfully, you will see output like this:
If the application does not start successfully, type cf logs < your app name > -recent to view the error logs. Check manifest.yml for errors, such as tabs in place
of whitespace.
Now, visit the Map app at http://<app>.mybluemix.net. You will see the simulated
vehicles moving across the map. Click on a vehicle to view the telemetry data.
Page 12 of 31
IBM WebSphere Technical University
6.3
Increase the vehicle count per simulator
Each vehicle simulator can model multiple vehicles. The number of vehicles is
controlled by a Bluemix environment variable, which can be set from the Bluemix
application dashboard.
In the dashboard, click on the SDK for Node.js™ icon.
Page 13 of 31
IBM WebSphere Technical University
Add a USER-DEFINED variable VEHICLE_COUNT, and select a value of 5.
Notice that the change was applied dynamically and the number of cars on the map
increases.
7 Using the Tester app
The Tester app is used to send commands to the simulated vehicles and the Map
app. The vehicle simulator subscribes to commands of type setProperty and will
dynamically change its own properties, speed, and state. The Map app subscribes to
commands of type addOverlay and will dynamically display a popup of text over a
vehicle.
Open the Map app and Tester app (http://<app>.mybluemix.net/tester) side-byside, so that you can see both windows.
7.1
setProperty
Select a vehicle, then enter the ID in the second form on the Tester page. Enter a
property of speed and a value of 120, and press 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 120 km/hr.
Page 14 of 31
IBM WebSphere Technical University
The vehicles simulate a set of static properties (location, speed, state, and type)
and custom properties. The setProperty API allows you to dynamically
add/change/delete a custom property on a vehicle. To add a property, simply
publish a property that doesn't yet exist. For example, use property =
driverWindow and value = 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.
7.2
addOverlay
The Map app subscribes to commands of type addOverlay, to allow external
applications to display messages on the map over a vehicle. In the Tester app, use
the upper form to display a message over a vehicle, for example:
Page 15 of 31
IBM WebSphere Technical University
8 Configuring the Geospatial Analytics service
The Bluemix Geospatial Analytics service allows you track when devices enter or
leave defined regions, or geofences. The Map app can interact with the Bluemix
Geospatial Analytics service, allowing you to graphically create and delete geofences
dynamically. The Geospatial Analytics service uses the IoT Foundation organization
API key you created previously to subscribe to device location data.
In your Bluemix dashboard, select Add Service, then choose the Geospatial
Analytics service. Enter a service name (ex: geo-trafficsim) and bind the service to
the Connected Vehicle app. Select Create, and wait for the application to re-stage.
Page 16 of 31
IBM WebSphere Technical University
The Connected Vehicle application includes APIs to start and stop the Geospatial
Analytics service. To start the service, visit the following URL in your browser and
wait for the page to return {} (may take 45-60 seconds):
http://<app>.mybluemix.net/GeospatialService_start
Now, open the Map app (http://<app>.mybluemix.net) and create some geofences.
Use the Alert button on the toolbar to start the geofence creation process, and drag
the handles and edges to position the geofence. To create the geofence, click on the
center black circle to open the context menu then select Create.
Page 17 of 31
IBM WebSphere Technical University
The Geospatial Analytics service will add this geofence to the list of watched areas,
and will publish an MQTT message through IoT Foundation whenever a vehicles
enters or leaves the area. The Map app will consume the message and display an
overlay over the vehicle on the map:
To delete a geofence, select the region and press the Delete button.
This concludes the main focus of the lab. At this point, you have created a Bluemix
account and deployed a connected vehicle application utilizing Internet of Things
Foundation and the Bluemix Geospatial Analytics service.
9 [Extra] Extend the application with Node-RED
With any remaining time in the lab, you will use the Node-RED boilerplate in Bluemix
to extend the connected vehicle application. Node-RED is a visual tool for wiring
together events in IoT use cases. Node-RED allows you to design flows of logic that
Page 18 of 31
IBM WebSphere Technical University
link a variety of inputs (ex. MQTT, TCP, HTTP) to outputs (ex. MQTT, HTTP, Twitter,
MongoDB, Cloudant) to quickly add business logic to a scenario.
9.1
Deploy Node-RED in Bluemix
Node-RED is available as a boilerplate application in Bluemix. Open the Bluemix
dashboard for the same organization and space where the Connected Vehicle
application was deployed. Select Add Application, and choose the Internet of
Things Foundation boilerplate.
Provide a name and hostname (ex: bryancboyd-nodered), and press Create. The
application will take up to a minute to deploy.
When the application is running, select Bind a Service and choose the IoT
Foundation service you created previously (ex. iot-trafficsim). Select Add and wait
for the application to restage.
After the application stages, open the Node-RED canvas at the following URL:
http://<node-red-app>.mybluemix.net/red
The IoT boilerplate Node-RED applications starts with a default flow. Select the
nodes on the canvas and press delete to remove them.
9.2
Flow 1: Monitor Vehicle Telemetry
For the first flow, we are going to monitor telemetry for all vehicles. Drag an ibmiot
input node from the palette on the left onto the canvas. Drag a debug node to the
right of the ibmiot node, and wire the nodes together. Double-click the ibmiot node
to enter an edit dialog, and configure it like this:
Authentication: Bluemix Service
Input Type: Device Event
Device Type: vehicle
Device Id: <all>
Event: telemetry
Format: json
Name: Telemetry
Now press Deploy (top-right corner of page) and select the debug pane. If
configuration was successful and the connected vehicle application is currently
Page 19 of 31
IBM WebSphere Technical University
running, you will see the MQTT payloads for the connected vehicles in the debug
pane.
Page 20 of 31
IBM WebSphere Technical University
If your VEHICLE_COUNT environment variable is set to a value greater than 1, the
telemetry data for VEHICLE_COUNT vehicles will be contained in a single array. To
modify the flow to filter for a single vehicle (ex. ABC-2), add a function node in the
middle of your flow, double-click 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 press Deploy. You should now see data for a single
vehicle in your debug pane:
To import this example into your Node-RED application, select Import... à
Clipboard... and paste in the following:
[{"id":"4078e26.fbf871c","type":"ibmiot in","authentication":"boundService","apiKey":"","inputType":"evt","deviceId":"
","applicationId":"","deviceType":"vehicle","eventType":"telemetry","commandTy
pe":"","format":"json","name":"Telemetry","service":"registered","allDevices":
true,"allApplications":"","allDeviceTypes":"","allEvents":"","allCommands":"",
"allFormats":"","x":119.52381134033203,"y":82.85714530944824,"z":"7334b438.8cc
Page 21 of 31
IBM WebSphere Technical University
b4c","wires":[["e2f33833.1d0cc8"]]},{"id":"e1fcad1f.1e035","type":"debug","nam
e":"","active":true,"console":"false","complete":"false","x":479.9999847412109
4,"y":82.22222137451172,"z":"7334b438.8ccb4c","wires":[]},{"id":"e2f33833.1d0c
c8","type":"function","name":"filter","func":"var data = msg.payload;\nfor (var i in data) { \n\tif (data[i].id == \"ABC-­‐2\") { \t\n\t\tmsg.payload = data[i]; \n\t\treturn msg; \n\t}\n}","outputs":1,"x":301.11109161376953,"y":98.88888835906982,"z":"7334b4
38.8ccb4c","wires":[["e1fcad1f.1e035"]]}] 9.3
Flow 2: Remote Control
Next, use Node-RED to build a simple remote control to lock/unlock a vehicle. You
will use two inject nodes: one to unlock the vehicle, the other to lock it. For each
operation, you will publish a setProperty command for property lockState with a
value of "locked" or "unlocked", then publish an addOverlay command to display a
notification on the Map app.
First, use the Tester application to set the lockState manually. The Tester
application will show the MQTT topic and JSON payload that is published to the
vehicle. Open http://<app>.mybluemix.net/tester/ in a browser, and update a
property (ex. lockState, value of locked)
Now use the Tester app to publish a "Locked!" overlay message over the vehicle.
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"
Page 22 of 31
IBM WebSphere Technical University
for the other. This payload will be the value that is sent in the setProperty
command.
Next, add a function node to the flow and wire both inject nodes to it. This function
will build and publish two commands to IoT Foundation: one for setting the vehicle
state, 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
Page 23 of 31
IBM WebSphere Technical University
})
}
return [ [setPropertyMsg, addOverlayMsg] ];
Next, 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:
Now deploy the application (click Deploy in the top-right corner of the page) and
press the button on the inject nodes while watching the Map app. You will see the
lockState property update for vehicle ABC-2, and a message will appear on the map:
Page 24 of 31
IBM WebSphere Technical University
To import this example into your Node-RED application, select Import... à
Clipboard... and paste in the following:
[{"id":"39b55e35.c64aa2","type":"inject","name":"","topic":"","payload":"locke
d","payloadType":"string","repeat":"","crontab":"","once":false,"x":122,"y":61
,"z":"82444a5d.7dbbb8","wires":[["15886565.ea779b"]]},{"id":"4811a619.b7ee58",
"type":"inject","name":"","topic":"","payload":"unlocked","payloadType":"strin
g","repeat":"","crontab":"","once":false,"x":123,"y":118,"z":"82444a5d.7dbbb8"
,"wires":[["15886565.ea779b"]]},{"id":"15886565.ea779b","type":"function","nam
e":"build commands","func":"var commandValue = msg.payload;\n\nvar setPropertyMsg = {\n\ttopic: \"iot-­‐
2/type/trafficsim/id/ABC/cmd/setProperty/fmt/json\",\n\tpayload: JSON.stringify({\n\t\t\"id\": \"ABC-­‐16\",\n \t\"property\": \"lockState\",\n \t\"value\": commandValue\n\t})\n}\n\nvar addOverlayMsg = {\n\ttopic: \"iot-­‐2/type/api/id/tester/cmd/addOverlay/fmt/json\",\n\tpayload: JSON.stringify({\n\t\t\"id\": \"ABC-­‐16\",\n \t\"text\": commandValue,\n \t\"duration\": 5000\n\t})\n}\n\nreturn [ [setPropertyMsg, addOverlayMsg] ];","outputs":1,"x":314,"y":87,"z":"82444a5d.7dbbb8","wires":[["f4a0c41f.0b5f3
8","16a019e9.e95fe6"]]},{"id":"f4a0c41f.0b5f38","type":"iot-­‐app-­‐
out","name":"send","topic":"","x":529,"y":113,"z":"82444a5d.7dbbb8","wires":[]
},{"id":"16a019e9.e95fe6","type":"debug","name":"","active":true,"console":"fa
lse","complete":"false","x":507,"y":59,"z":"82444a5d.7dbbb8","wires":[]}] 9.4
Flow 3: Simulate a Person
In its most basic form, the provided vehicle simulator is just a simulator—one that
can model any properties and follow a road path. To simulate a person rather than a
Page 25 of 31
IBM WebSphere Technical University
vehicle (say, an elderly woman), you can change the properties of a simulated
"vehicle" dynamically.
In the Node-RED flow, drop and inject input node onto the canvas. Edit the node,
to provide a string payload of ABC-2.
Add a function node after the inject node, and insert the following code:
var id = msg.payload;
var msgs = [];
var propValues = [
// static properties
["speed", "2"],
["state", "walking"],
["description", "Out for a nice walk"],
// custom properties
["customProp", ""],
["age", 87],
["sex", "female"],
["name", "Albertine"]
];
for (var i in propValues) {
msgs.push({
deviceId: "ABC",
deviceType: "vehicle",
eventOrCommandType: "setProperty",
format: "json",
payload: JSON.stringify({
"id": id,
"property": propValues[i][0],
"value": propValues[i][1]
})
});
}
// make map overlay
msgs.push({
deviceId: "tester",
deviceType: "api",
eventOrCommandType: "addOverlay",
format: "json",
payload: JSON.stringify({
"id": id,
Page 26 of 31
IBM WebSphere Technical University
"text": "Hello Grandmother!",
"duration": 5000
});
})
return [msgs];
After the function node, add a ibmiot node with the following properties:
Press the inject node, and you will see the properties of vehicle ABC-2 change to
model a person moving 2 km/hr.
Page 27 of 31
IBM WebSphere Technical University
To import this example into your Node-RED application, select Import... à
Clipboard... and paste in the following:
[{"id":"d45a1fb3.2ba5e","type":"inject","name":"","topic":"","payload":"ABC-­‐
2","payloadType":"string","repeat":"","crontab":"","once":false,"x":116.666666
66666666,"y":81.11111111111111,"z":"7334b438.8ccb4c","wires":[["e92fc3e5.16d04
"]]},{"id":"a4bcec6b.5b431","type":"ibmiot out","authentication":"boundService","apiKey":"","outputType":"cmd","deviceId"
:"override","deviceType":"override","eventCommandType":"override","format":"js
on","data":"override","name":"set Grandmother","service":"registered","x":457.7777786254883,"y":80,"z":"7334b438
.8ccb4c","wires":[]},{"id":"1631a938.e9ce57","type":"debug","name":"","active"
:true,"console":"false","complete":"false","x":426.66666666666663,"y":141.1111
1111111111,"z":"7334b438.8ccb4c","wires":[]},{"id":"e92fc3e5.16d04","type":"fu
nction","name":"build cmds","func":"var id = msg.payload;\nvar msgs = [];\n\nvar propValues = [\n\t// static properties\n\t[\"speed\", \"2\"],\n\t[\"state\", \"walking\"],\n\t[\"description\", \"Out for a nice stroll\"],\n\n\t// custom properties\n\t[\"customProp\", \"\"],\n\t[\"age\", 87],\n\t[\"sex\", \"female\"],\n\t[\"name\", \"Albertine\"]\n];\n\nfor (var i in propValues) {\n\tmsgs.push({ \n\t\tdeviceId: \"ABC\",\n\t\tdeviceType: \"vehicle\",\n\t\teventOrCommandType: \"setProperty\",\n\t\tformat: \"json\",\n\t\tpayload: JSON.stringify({\n\t\t\t\"id\": id,\n \t\t\"property\": propValues[i][0],\n \t\t\"value\": propValues[i][1]\n\t\t})\n\t});\t\n}\n\n// make map Page 28 of 31
IBM WebSphere Technical University
overlay\nmsgs.push({\n\tdeviceId: \"tester\",\n\tdeviceType: \"api\",\n\teventOrCommandType: \"addOverlay\",\n\tformat: \"json\",\n\tpayload: JSON.stringify({\n\t\t\"id\": id,\n \t\"text\": \"Hello Grandmother!\",\n \t\"duration\": 5000\n\t})\n});\n\nreturn [msgs];","outputs":1,"x":268.88888359069824,"y":104.4444408416748,"z":"7334b43
8.8ccb4c","wires":[["a4bcec6b.5b431","1631a938.e9ce57"]]}] 9.5
Flow 4: Tweet my Child's Driving
With the Bluemix Geospatial Analytics service, you can create geofence polygons in
the Map app and receive IoT Foundation 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 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 my
vehicle has entered a geofence surrounding my house, and notify my house
automation system to prepare for my arrival.
You can use Node-RED to link geofence alerts to other applications and APIs. In this
flow, you will publish a Twitter tweet when receiving a geofence notification
message for a particular vehicle.
First, drop an ibmiot input node onto the canvas. Configure the node as follows:
Add a function node after the ibmiot input node. This function wil filter the data
returned from the geospatial service, and only continue flow execution 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), wire the function to a debug node, and
deploy:
Page 29 of 31
IBM WebSphere Technical University
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; }
[Note: the following section requires a Twitter account. If you do not have one, sign
up at http://www.twitter.com]
Next, drag a twitter output node onto the canvas, and wire the output of the
function to the input of this node. The twitter node allows you to configure an
existing Twitter account using OAuth, then will tweet the contents of msg.payload.
Sign in to your Twitter account, then 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;
}
Deploy the application, and Node-RED will publish a tweet whenever a geofence is
crossed by your vehicle:
Page 30 of 31
IBM WebSphere Technical University
9.6
Develop further scenarios
With any remaining time, try to build a new and unique scenario with Node-RED and
the Connected Vehicle application. Or, continue to work on this lab after WebSphere
Technical University, with your Bluemix account.
Page 31 of 31