After we have registered our IoT device, we can start to develop it. AWS provides a complete AWS IoT SDK for several languages at https://aws.amazon.com/it/iot/sdk/. For our test, we will use the JavaScript SDK. We assume that Node.js already installed.
From the GitHub repository at https://github.com/aws/aws-iot-device-sdk-js, clone the examples and install the SDK. We need to open a Command Prompt. From the root directory in which we saved our certificates, we can run the following command:
$ npm init
Accept all the proposed options, then enter the following:
$ npm install aws-iot-device-sdk
We have now installed the Node.js client, so we can start to write our simple client, but we need the endpoint URL. From the Settings option, we have to copy the custom endpoint, as shown in the following screenshot:
We can now write our simple client using the following code:
var awsIot = require('aws-iot-device-sdk');
const clientId = 'my-iiot-book-device';
var certPath='fc958ed3d2-';
var device = awsIot.device({
keyPath: certPath + 'private.pem.key',
certPath: certPath + 'certificate.pem.crt',
caPath: 'root-CA.pem',
clientId: clientId,
host: 'XXXXXXXX.iot.eu-central-1.amazonaws.com'
});
console.log(device);
device
.on('connect', function() {
console.log('connect');
console.log('publishing');
for (var i=0; i<100; i++) {
console.log("sent " + i);
device.publish('signals/'+clientId, JSON.stringify({ ‘temperature': i}));
}
});
device
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
Our client simply connects to the AWS IoT Core and publishes a test message. We can test the data that is sent with the test console.
Click on the Test option and subscribe to the signals/# topic, as shown in the following screenshot: