In this section, we will develop a sensor publisher. A sensor publisher is a system that generates sensor data and then perform to publish that sensor to a certain server. We can implement this application by using Node.js. Ensure your computer has Node.js installed. A sensor publisher will send sensor data at certain periods. For the demo, I generated a random value between 10 and 35 for the temperature sensor. Consider the following steps:
- Firstly, we create a folder named sensor-publisher and initialize the project using npm init:
$ mkdir sensor-publisher
$ cd sensor-publisher/
$ npm init
- Then, we install AWS IoT SDK for JavaScript/Node.js. For this, type the following command:
$ npm install aws-iot-device-sdk --save
- Insert the certificate and private key files from the IoT device that have been obtained from AWS IoT. Moreover, we continue to write the program. Create a file, sensor-publisher.js. Write the following complete program in this file:
var awsIot = require('aws-iot-device-sdk');
var device = awsIot.device({
keyPath: 'xxxx-private.pem.key',
certPath: 'xxxx-certificate.pem.crt',
caPath: 'root-CA.pem',
host: '<host>.iot.<region>.amazonaws.com',
clientId: 'user-testing',
region: '<region>'
});
device
.on('connect', function() {
console.log('connected to AWS IoT.');
setInterval(function(){
// random 10 - 35
var data = {
'temperature': Math.floor((Math.random() * 35) + 10)
};
device.publish('iot/sensor', JSON.stringify(data));
console.log('sent: ', JSON.stringify(data));
}, 3000);
});
console.log('Sensor publisher started.');
In the preceding code, change the following values:
-
- keyPath is the private key from the IoT device
- certPath is the certificate file from the IoT device
- caPath is the certificate file for AWS IoT
- <host> is the hostname for AWS IoT
- <region> is a region name for your AWS
This program will send data on the iot/sensor topic every 3 seconds. To send data to AWS IoT, we call the device.publish() function. Sensor data is built in JSON format; for instance, a sample of sensor data in JSON:
{ 'temperature': 23 }
In the next section, we will develop a frontend application, web app, to consume sensor data from AWS IoT.