Getting started with AWS IoT Device SDK

The AWS IoT Device SDK is a quick and easy way to connect your IoT devices with AWS IoT Core. To date, AWS provides IoT Device SDKs for Node.js, Java, Python, and Embedded C. For this particular section, we will be connecting our dummy IoT device with AWS IoT, using the Node.js SDK.

Before we get things started, ensure that you have the latest versions of node and NPM installed and running on your device. Since we are simulating an IoT device using an Ubuntu virtual machine, you can use the following commands to install and verify node and NPM versions:

# sudo apt-get update 
# sudo apt-get install nodejs npm 
# node -v && npm -v 

Once the required packages are installed, we now need to install the AWS IoT Device SDK itself. Type in the following command as shown:

# npm install aws-iot-device-sdk 

With the SDK installed, we can now begin testing the connectivity with a simple Node.js program. Copy and paste the following code snippet in a new .js file on your IoT device:

# vi test1.js 
//Connection parameters 
var awsIot = require('aws-iot-device-sdk'); 
var device = awsIot.device({ 
   keyPath: '<PATH_TO_PRIVATE.PEM.KEY>', 
  certPath: '<PATH_TO_CERTIFICATE.PEM>CRT>', 
    caPath: 'root-CA.crt', 
  clientId: '<THING_NAME>', 
    region: '<REGION>', 
      host: '<IoT_DEVICE_REST_API_ENDPOINT>' 
}); 
//Connection parameters end 
 
//Device Object 
device 
.on('connect', function () { 
console.log('Yaaa! We are connected!'); 
}); 

What does the code do? Well for starters, the first section of the code is simply where you pass the required private key and certificates downloaded from the earlier steps, along with a few other configuration items, such as the clientId, the AWS region where the IoT Core is set up and finally, the host, which is basically a unique REST API endpoint for your device. You can find this endpoint by selecting your newly created IoT device from the AWS IoT dashboard and selecting the Interact tab, as shown in the following screenshot:

The second part of the code is where we use the configured parameters to actually connect to the AWS IoT Core. If the connection is successful, it will print a simple message as shown. To run the code, simply type in the following command:

# node test1.js 

With the device now successfully connecting with the AWS IoT Core, let's look at a few other examples that you can use to interact with the message broker service. To start off, let's see how we can use the AWS IoT Device SDK to subscribe to a topic and print back any message that gets published to it.

Copy and paste the following code snippet below the connection parameters:

# vi test2.js 
//Connnection parameters 
. . . . . 
//Connection parameters end 
 
//Device Object 
device 
.on('connect', function () { 
console.log('Yaaa! We are connected!'); 
device.subscribe('Topic0'); 
console.log('Subscribed to Topic'); 
}); 
 
device 
.on('message', function (topic, payload) { 
console.log('Received following message: ', topic, payload.toString()); 
}); 

The following code subscribes the device to a topic named Topic0. Once the subscription is completed, the code will display any message that is published to it.

With the code in place, save the file and run the program using the following code:

# node test2.js 

Next, let us look at how we can publish a message to the newly created topic:

  1. To publish a message to the following topic, we will use the MQTT client provided by AWS IoT Core itself. To do so, from the AWS IoT Core dashboard, select the Test option from the navigation pane.
  2. Using the MQTT client, you can subscribe, as well as publish, to a topic. Click on the Publish to topic option.
  1. In the Publish section, provide the topic name (in this case, Topic0) where you want to publish the message and click on Publish to topic, as shown in the following screenshot:

Check the device Terminal for the corresponding message. You should see the following output:

With the device now able to subscribe to a topic, you can also get the device to publish a message to a topic as well.

Once again, create a new file and copy-paste the following code snippet below the connection parameters:

# vi test3.js 
//Connnection parameters 
. . . . . 
//Connection parameters end 
 
//Device Object 
device 
.on('connect', function () { 
console.log('Yaaa! We are connected!'); 
device.subscribe('Topic0'); 
console.log('Subscribed to Topic'); 
var msg = "Hello from IoT Device!"; 
      device.publish('Topic0', msg); 
      console.log ("Publishing message: "+msg); 
}); 
 
device 
.on('message', function (topic, payload) { 
console.log('Received following message: ', topic, payload.toString()); 
}); 

As you can see from the following code, we have simply added a publish() method that will publish a custom message to a pre-defined topic, in this case, Topic0.

Save the code and run the program using the following command:

# node test3.js 

You should get the following output from the device Terminal:

Simple, isn't it! You can use the same concepts on a real IoT device as well, with only a few minor changes here and there. Here is an example code snippet that you can use to generate dummy data and publish the data to an MQTT topic.

Create a new file and paste the following code snippet below the connection parameters, as done throughout this section:

# vi test4.js 
//Connnection parameters 
. . . . . 
//Connection parameters end 
 
var uuid = require('node-uuid'); 
var numbers = new Array(10); 
function getRandomInt(min, max) { 
  return Math.floor(Math.random() * (max - min + 1)) + min; 
} 
 
device 
.on('connect', function () { 
console.log('Yaaa! We are connected!'); 
device.subscribe('Topic0'); 
console.log('Subscribed to Topic'); 
 
for (var i = 0; i < numbers.length; i++) 
    { 
  for (var j = 0; j < numbers.length; j++) 
     { 
       numbers[i] = getRandomInt(0,1); 
       uuid[i] = uuid.v4() 
      } 
      var msg = "{"uuid":"" + uuid[i] + """ + "," +"""+ "state":" + numbers[i]+"}"; 
      device.publish('Topic0', msg); 
      console.log ("Publishing message: "+uuid[i],numbers[i]); 
   } 
 
}); 
 
device 
.on('message', function (topic, payload) { 
console.log('Received following message: ', topic, payload.toString()); 
}); 

The following code snippet leverages the node-uuid module to randomly generate long strings of UUIDs. With each UUID record generated, a corresponding random value of either 0 or 1 is printed which denotes the state of the UUID. You can control the number of records generated by adjusting the value of the array object. By default, the following code will publish 10 records in a proper JSON to the MQTT topic, as shown in the following code snippet:

{ 
"uuid":"357d6212-3444-4f55-9784-93a265905289", 
"state":0 
} 
{ 
"uuid":"ad8cb61b-f29d-4a84-a7eb-42633dd3a3c2", 
"state":0 
} 
. . . . .  
{ 
"uuid":"19492c45-0cf7-4468-b275-5b7b1bdf3a64", 
"state":1 
} 

Once the code is in place, simply execute it using the following command:

# node test4.js 

With this, we come to the end of this particular section. In the next section, we will be looking at how we can integrate the AWS IoT Core with other AWS Services, using simple IoT rules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset