AWS IoT Core v2
This library is a built-in class that provides functions to communicate with AWS IoT Core.
Library usage requirements | |
---|---|
Type | Integrations |
Name | AWS_IoT_Core_V2 |
Version | 2020-11-04 |
Code size used | 2.3KB |
Resources used | HTTPS x 1, MQTT x 1, Timers x 1 |
Related Documents
For information on the AWS IoT API used in this library, please refer to the documentation.
Abstracts
Methods()/Properties | Summary |
---|---|
new AWS_IOT_CORE() | Initializes the AWS_IOT_CORE object with the passed configuration. |
{AWS_IOT_CORE} Instance
Methods()/Properties | Summary |
---|---|
.httpPost() | Send data over HTTPS to an AWS IoT Core endpoint. |
.abortHttpRequest() | Abort the currently ongoing HTTP request. |
.mqttConnect() | Connect to AWS IoT Core over MQTT. |
.errors | An array containing the invalid configuration key names. Exists only when an invalid configuration is passed to setConfig or the constructor. |
Details
new AWS_IOT_CORE(config)
Initializes the AWS_IOT_CORE
instance with the passed configuration.
Configuration
When instantiating the AWS_IOT_CORE
instance, the following configuration options are mandatory:
Name | Type | Default | Summary |
---|---|---|---|
host | string | MANDATORY | The AWS IoT endpoint for requests, found on the AWS IoT Core console settings page. |
deviceCert | string | MANDATORY | The X.509 certificate associated with this device. |
devicePrivKey | string | MANDATORY | The private key associated with this device. |
ca | string | MANDATORY | The root CA necessary to connect to AWS IoT Core. |
timeout | Number | 90000 | HTTP request timeout, in ms. |
config
must be a JavaScript object in the following form:
var config = {
host: "<String>",
deviceCert: "<String>",
devicePrivKey: "<String>",
ca: "<String>",
timeout: "<Number>"
};
Once the configuration object has been created, it can be passed to AWS_IOT_CORE
during instance creation. If any invalid values are passed, the invalid key names are stored in the errors
property, and should be handled appropriately.
var iot = new AWS_IOT_CORE(config);
if ('errors' in iot) {
// TODO: handle errors
}
Setter Methods
After creating an instance of the AWS_IOT_CORE
object, each of the aforementioned configurations may be changed by its corresponding setter function. If an invalid value is passed to any setter, it returns false
.
Setter | Summary |
---|---|
.setHost(value: String) | Set the AWS IoT Core endpoint for requests. |
.setDeviceCert(deviceCert: String) | Set the certificate for your Thing. The certificate can be generated when the Thing is created in the AWS IoT Core console. Refer to the AWS IoT Core Documentation for more information on creating and activating the device certificate. Why is this information necessary? |
.setDevicePrivKey(devicePrivKey: String) | Set the private key for your Thing for use in authentication. The private key can be generated when the Thing is created in the AWS IoT Core console. Refer to the AWS IoT Core Documentation for more information on creating the private key. Why is this information necessary? |
.setTimeout(value: Number) | Set the HTTP request timeout. |
.setRootCA(value: String) | Set the root CA used for making requests. |
.setConfig(config)
The setConfig
function can be used to set or change multiple configuration options at the same time. This function expects a typical JavaScript object of key:value pairs as an argument. If any invalid values are passed, this returns an array containing the names of each invalid key, and sets the errors
property to that array. When a valid config
is passed to setConfig
, if errors
exists, it is removed.
iot.setConfig({
host: "value",
deviceCert: "value",
devicePrivKey: "value",
ca: "value",
timeout: 90000
});
Instance Methods
.httpPost(topic,headers,getNextChunk,callback[,qos])
Post data over HTTPS to the AWS IoT Core endpoint specified by topic
. Ensure that the proper AWS IoT Core Policies are set for the Thing before use.
Name | Type | Default | Summary |
---|---|---|---|
topic | string | MANDATORY | The MQTT Topic. |
headers | object | MANDATORY | The desired HTTP headers for this request. "Content-Length" is required for successful execution. |
getNextChunk | function | MANDATORY | Callback for retrieving the data to send. Returns data in [string/ArrayBuffer] chunks of 4KB or less until exhausted, then returns null . |
callback(err, resp) | function | MANDATORY | The user's callback function, to handle the response. Will pass an Error as err and a Response as resp . |
qos | Number | 0 | The desired QoS value for this request. AWS Documentation on QoS |
return | undefined | - | - |
Responses
This library uses an object to handle AWS IoT Core responses. These responses are always in the following format:
{
statusCode: <Number>,
statusMessage: <String>,
body: <String>
}
More details on statusCode
and statusMessage
can be seen in the HTTPS documentation for the appropriate device (NEQTO Bridge | Spresense).
body
is the HTTP response data.
Errors
This library passes an Error object from HTTP errors into the user-provided callback. Error objects have the following form:
{
errCode: <Number>
}
This errCode
parameter has more information in the appropriate neqto.js documentation (NEQTO Bridge | Spresense).
.abortHttpRequest()
Abort the currently ongoing HTTP request.
Name | Type | Default | Summary |
---|---|---|---|
return | undefined | - | - |
.mqttConnect([options])
Establish a connection with the AWS IoT Core MQTT endpoint. Ensure that the proper AWS IoT Core Policies are set for the Thing before use.
Name | Type | Default | Summary |
---|---|---|---|
options | object | {} | The options object from the neqto.js mqtt.connect method. |
return | MQTT.Client | - | An MQTT Client connected to AWS IoT Core. See the device's appropriate MQTT page for more details on this object. - NEQTO Bridge - Spresense - AWS Documentation on QoS |
Usage Examples
Click here to learn how to get the CA
that can be used in the config
option.
Verify that the root CA is appropriate for the target IoT Core endpoint.
var rootCa = '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----';
The following sample code sections all use the following configuration:
// IMPORTED LIBRARIES
// - AWS_IoT_Core_V2
// Logging setup
log.setLevel(0,2); //-1:NONE 0:ERROR 1:WARNING 2:DEBUG 3:TRACE, 0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
log.printLevel(2); //0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
// Device setup
var deviceCert = "[certificate]";
var deviceKey = "[key]";
var host = "host.iot.ap-northeast-170.amazon.aws.com"
var config = {
host: host,
deviceCert: deviceCert,
devicePrivKey: deviceKey,
ca: rootCa
}
var iotCore = new AWS_IOT_CORE(config);
if ('errors' in iotCore) {
// TODO: handle errors
throw 'Invalid configuration'
}
Sample 1: MQTT With Automatic Reconnection
var client = iotCore.mqttConnect( {reconnectCount: 1855} );
if (!client) {
throw 'Failed to create mqtt instance';
}
client.on('error', function(err) {
print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
//TODO: Error handling
});
client.on('message', function(topic, message) {
print('TOPIC: ' + topic + ' MESSAGE: ' + message);
//TODO: Message handling
});
client.on('connect', function() {
print("CONNECTED");
client.subscribe("testtopic/subtopic/#", { qos: 1 }, function(err) {
if (err.code > 0) {
print("MQTT SUBSCRIBE ERROR", err.code);
//TODO: Error handling
}
});
client.subscribe("shadowtopic/#", { qos: 1 }, function(err) {
if (err.code > 0) {
print("MQTT SUBSCRIBE ERROR", err.code);
//TODO: Error handling
}
});
});
setInterval(function() {
if (client.canPublish()) {
var body = JSON.stringify({ "message" : "dummy" })
client.publish("testtopic/subtopic/dummy", body, { qos: 1 }, function(err){
if(err.code == 0){
print('Publish OK');
} else {
print('Publish failed');
//TODO: Error handling
}
});
} else {
print('Cannot publish');
}
}, 15000);
Sample 2: MQTT With Manual Reconnect
var reconnectAttempts = 0;
var maxReconnectAttempts = 24;
var registerEventHandlers = function(mqClient) {
if (!mqClient) {
return;
}
mqClient.on('error', function(err) {
print('ERROR: ' + err.code + ' ERRNO: ' + mqClient.get('errnoConnect'));
if (err.code == 1) { //Connection failed
if (reconnectAttempts++ < maxReconnectAttempts) {
print('reconnectAttempts:', reconnectAttempts);
mqClient.reconnect();
} else {
print('ABORT');
reconnectAttempts = 0;
mqClient.end(); //Release mqtt instance
client = undefined;
}
}
});
mqClient.on('message', function(topic, message) {
print('TOPIC: ' + topic + ' MESSAGE: ' + message);
//TODO: Message handling
});
mqClient.on('close', function() {
print("DISCONNECTED");
mqClient.reconnect();
});
mqClient.on('connect', function() {
reconnectAttempts = 0;
print("CONNECTED");
mqClient.subscribe("testtopic/subtopic/#", { qos: 1 }, function(err) {
if (err.code > 0) {
print("MQTT SUBSCRIBE ERROR", err.code);
//TODO: Error handling
}
});
});
}
client = iotCore.mqttConnect();
if (!client) {
throw 'Failed to create mqtt instance';
}
registerEventHandlers(client);
setInterval(function() {
if (!client) {
print('mqtt instance recreate');
client = iotCore.mqttConnect();
registerEventHandlers(client);
}
if (client && client.canPublish()) {
var body = JSON.stringify({ "message" : "dummy" });
client.publish("testtopic/subtopic/dummy", body, { qos: 1 }, function(err){
if(err.code == 0){
print('Publish OK');
} else {
print('Publish failed');
//TODO: Error handling
}
});
}
}, 15000);
Sample 3: Basic HTTP Usage
var body = JSON.stringify({
"message": "HTTP post"
});
var headers = {
"Content-Length": body.length.toString()
}
// A simple method that returns `body` once, then `null` all other times.
var getBody = function() {
var temp = body;
body = null;
return temp;
}
// A very simple callback to handle the HTTP response
var callback = function(err, res) {
if (err) print(JSON.stringify(err));
if (res) print(JSON.stringify(res));
}
iotCore.httpPost("testtopic/shadowtopic/dummy", headers, getBody, callback);
Sample 4: HTTP with Chunks
var body = JSON.stringify({
"message": "This is a really long string[...]"
});
var headers = {
"Content-Length": body.length.toString()
}
// This is a *dummy* example of how to chunk data for return.
// If the data is actually larger than 4KB, it is best to chunk it in the way that makes most sense.
var index = 0;
var getBody = function() {
var ival = 8;
var ret = body.substring(index, index + ival);
if (ret) {
index = index + ival;
return ret;
}
return null;
}
// A very simple callback to handle the HTTP response
var callback = function(err, res) {
if (err) print(JSON.stringify(err));
if (res) print(JSON.stringify(res));
}
iotCore.httpPost("testtopic/shadowtopic/dummy", headers, getBody, callback);