NEQTO Docs
  • Languages iconEnglish
    • 日本語
  • Docs
  • Region API
  • Global API
  • FAQ

›Integration

Getting Started

  • NEQTO Hello World!
  • Step 1. Console Settings
  • Step 2. Device Setting & Start Service

    • When using NEQTO Bridge
    • When using Spresense
  • Step 3. Using Sensors

NEQTO

  • NEQTO Account Registration
  • API Usage
  • Batch Registration
  • Support Guidelines

NEQTO Console

  • Introduction
  • Fundamentals
  • Administrative Actions
  • Device Management
  • Scripts
  • Actions and Contacts
  • NEQTO Apps
  • Machine Driver
  • Recommended Browsers
  • Billing Information

SPRESENSE

    Hardware Specifications

    • 01. About Spresense

    Software Specifications

    • 01. Operational Flow
    • 02. Initial Installation
    • 03. Spresense Wi-Fi Initial Setup
    • 05. Debug Log Acquisition
    • 06. System LED Indications
    • 07. Event Messages
    • 08. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 10. RTC
    • 12. GPIO
    • 13. UART
    • 15. I2C
    • 17. Camera
    • 18. nqSpresense
    • 19. nqService
    • 20. nqMqtt
    • 21. nqFOTA
    • 22. nqWiFi

NEQTO Bridge Series

    Hardware Specifications

    • 01. NEQTO Bridge Module
    • 02. NEQTO Bridge Wi-Fi Module
    • 03. NEQTO Bridge LTE-1 Module
    • 04. NEQTO Bridge LTE-M/NB Module
    • 05. NEQTO Bridge IO Board
    • 06. NEQTO Bridge Digital IO Board

    Software Specifications

    • 01. Operational Flow
    • 02. NEQTO Bridge Wi-Fi Module Initial Setup
    • 03. NEQTO Bridge LTE Module Initial Setup
    • 04. Debug Log Acquisition
    • 05. System LED Indications
    • 06. Event Messages
    • 07. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. UserSW
    • 12. GPIO
    • 13. UART
    • 14. SPI
    • 15. I2C
    • 16. ADC
    • 17. BLE
    • 18. nqBridge
    • 19. nqService
    • 20. nqMqtt
    • 21. nqFOTA
    • 22. nqWiFi
    • 23. nqLte
    • 24. nqLAN
    • 25. nqEx

neqto.js Libraries

    I2C

    • LIS2DW12 v2 Accelerometer
    • HTS221 v2 Temperature and Humidity Sensor
    • [Archive] LIS2DW12 Accelerometer
    • [Archive] HTS221 Temperature and Humidity Sensor

    Integration

    • AWS IoT Core v2 Library
    • AWS S3 v2 Library
    • Azure IoT v2 Library
    • GCP IoT Core Library
    • [Archive] AWS S3 Library
    • [Archive] AWS IoT Core Library

neqto.js Snippets

  • DataDog Snippet
  • Dropbox Snippet
  • Google Sheets Snippet
  • InfluxDB Snippet
  • Oracle Cloud Object Storage Snippet
  • Salesforce Snippet
  • SAP Cloud Platform Internet of Things Snippet
  • Splunk Snippet
  • Niagara Snippet

Release Notes

  • NEQTO Console Updates
  • NEQTO Firmware (Bridge Wi-Fi/LTE Module) Releases
  • NEQTO Firmware (Spresense Wi-Fi) Releases

AWS IoT Core v2 Library

CategoryLibraryLibrary VersionSizeNEQTO BridgeSPRESENSE
IntegrationsAWS_IoT_Core_V22020-11-04 (latest)2.3KBv01.00.00+v01.00.01+
IntegrationsAWS_IoT_Core_V22020-09-072.2KBv01.00.00+v01.00.01+

For information on how to import neqto.js libraries, please refer to this documentation.

This library uses the following resources:

  • HTTPS x 1
  • MQTT x 1
  • Timers x 1

Abstracts

Methods()/PropertiesSummary
new AWS_IOT_CORE()Initializes the AWS_IOT_CORE object with the passed configuration.

This library uses the AWS IoT API: https://docs.aws.amazon.com/iot/latest/developerguide/what-is-aws-iot.html

{AWS_IOT_CORE} Instance

Methods()/PropertiesSummary
.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.
.errorsAn 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:

NameTypeDefaultSummary
hoststringMANDATORYThe AWS IoT endpoint for requests, found on the AWS IoT Core console settings page.
deviceCertstringMANDATORYThe X.509 certificate associated with this device.
devicePrivKeystringMANDATORYThe private key associated with this device.
castringMANDATORYThe root CA necessary to connect to AWS IoT Core.
timeoutNumber90000HTTP 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.

SetterSummary
.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.

NameTypeDefaultSummary
topicstringMANDATORYThe MQTT Topic.
headersobjectMANDATORYThe desired HTTP headers for this request. "Content-Length" is required for successful execution.
getNextChunkfunctionMANDATORYCallback for retrieving the data to send. Returns data in [string/ArrayBuffer] chunks of 4KB or less until exhausted, then returns null.
callback(err, resp)functionMANDATORYThe user's callback function, to handle the response. Will pass an Error as err and a Response as resp.
qosNumber0The desired QoS value for this request.
AWS Documentation on QoS
returnundefined--

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.

NameTypeDefaultSummary
returnundefined--

.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.

NameTypeDefaultSummary
optionsobject{}The options object from the neqto.js mqtt.connect method.
returnMQTT.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

Object Usage Examples

The following is an example CA which can be used in the config option (as of 2020-07-20):

/* Amazon Root CA 1 - 066c9fcf99bf8c0a39e2f0788a43e696365bca */
var rootCa =  "-----BEGIN CERTIFICATE-----\nMIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\nADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\nb24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\nMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\nb3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\nca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\nIFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\nVOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\njgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\nAYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\nA4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\nU5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\nN+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\no/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\nrqXRfboQnoZsG4q5WTP468SQvvG5\n-----END CERTIFICATE-----";

Verify that the root CA is appropriate for the target IoT Core endpoint.

Please refer to the following resources:

  • AWS Documentation on Server Authentication
  • Amazon Trust Services

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);
The company names and product names mentioned above are registered trademarks or trademarks of their respective companies.

Updated: 2021-03-30
← [Archive] HTS221 Temperature and Humidity SensorAWS S3 v2 Library →
  • Abstracts
    • {AWS_IOT_CORE} Instance
  • Details
    • new AWS_IOT_CORE(config)
    • Setter Methods
    • Instance Methods
  • Object Usage Examples
    • Sample 1: MQTT With Automatic Reconnection
    • Sample 2: MQTT With Manual Reconnect
    • Sample 3: Basic HTTP Usage
    • Sample 4: HTTP with Chunks
AboutNewsProductsFAQPrivacy Policy}
NEQTO Console
IntroductionFundamentalsAdministrative ActionsDevice Management NEQTO Apps
NEQTO Bridge Series
NEQTO Bridge ModuleNEQTO Bridge Wi-Fi ModuleNEQTO Bridge LTE-1 ModuleError Logging Event Messages
API Documentation
API UsageGlobal APIRegional APIAPI Terms of Service
Jigsaw, Inc.
© 2021 JIG-SAW INC.