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

Azure IoT v2 Library

CategoryLibraryLibrary VersionSizeNEQTO BridgeSPRESENSE
IntegrationsAzure_IoT_V22020-11-042.8KBv01.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 AZURE_IOT()Initializes the AZURE_IOT instance with the passed configuration.

This library uses the Azure IoT Hub API: https://docs.microsoft.com/en-us/azure/iot-hub/

{AZURE_IOT} Instance

Methods()/PropertiesSummary
.generateSasToken()Generate the SAS token use for authenticating this device with Azure IoT Hub.
.httpPost()Post data to Azure IoT Hub via HTTPS.
.abortHttpRequest()Abort the currently ongoing HTTPS request.
.mqttConnect()Establish a connection with Azure IoT Hub 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 AZURE_IOT(config)

Initializes the AZURE_IOT instance with the passed configuration.

Configuration

When instantiating the AZURE_IOT object, the following configuration options are mandatory:

NameTypeDefaultSummary
hoststringMANDATORYA valid Azure IoT Hub endpoint; By default, the DNS name of an Azure IoT hub looks like {IoT Hub name}.azure-devices.net.
deviceIdstringMANDATORYThe device ID in Azure IoT Hub. This is created when a device is registered to the identity registry in Azure IoT Hub.
primaryKeystringMANDATORYThe service primary key for the desired Azure IoT Hub. This can be either the symmetric key from the identity registry, or a key from a shared access policy.
castringMANDATORYThe root CA for HTTP requests made by this instance.
timeoutnumber90000Defaults to 90000 milliseconds (90s). For HTTPS requests, changes the time before a request automatically times out.
tokenTimeoutnumber3600Defaults to 3600 seconds (1hr). Amount of time a generated SAS token is valid (in seconds).

config must be a JavaScript object in the following form:

var config = {
    host: "<String>",
    deviceId: "<String>",
    primaryKey: "<String>",
    ca: "<String>"
    timeout: "<Number>",
    tokenTimeout: "<Number>"
};

Once the configuration object has been created, it can be passed to AZURE_IOT 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 AZURE_IOT(config);
if ('errors' in iot) {
    // TODO: handle errors
}

Setter Methods

After creating an instance of the AZURE_IOT 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 host value for use in connecting to Azure IoT Hub. In the Azure IoT Hub Console, this value is the HostName from the "Primary Connection String" attribute when viewing a device.
.setDeviceId(value: String)Set the deviceId value for use in authenticating this device. The device_id value is found in the device details on the Azure IoT Hub console.
.setPrimaryKey(value: String)Set the primary_key value for use in authenticating this device. The primary_key value is found in the device details on the Azure IoT Hub console.
.setRootCA(value: String)Set the IoT Hub instance CA for making requests.
.setTimeout(value: Number)Set the HTTPS request timeout.
.setTokenTimeout(value: Number)Set the token timeout.

.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",
    deviceId: "value",
    primaryKey: "value",
    tokenTimeout: "value",
    timeout: "value"
});

Instance Methods

.generateSasToken([resourceUri[,signingKey[,policyName[,expiresInSecs]]]])

Generate the SAS token used for authenticating this device with Azure IoT Hub.

NameTypeDefaultSummary
resourceUristring{host}/devices/{deviceId}The URI for this device.
signingKeystring{primaryKey}The key used for signing the SAS token.
policyNamestringundefinedThe policy name for generating the security token, if applicable. This has different values depending on the value passed as primaryKey. The valid values are listed in the Azure IoT Hub security tokens documentation.
expiresInSecsstringtokenTimeoutThe token timeout.
returnstring-Authorization token used to establish an MQTT connection or make an HTTPS request

.httpPost(token,length,getBody,callback[,endpoint])

Post data to Azure IoT Hub via HTTPS.

Before use, ensure the proper permissions are set and that connecting this device is allowed within IoT Hub limits.

NameTypeDefaultSummary
tokenstringMANDATORYThe token used for authentication, returned from generateSasToken
lengthnumberMANDATORYTotal amount of data to send to Azure IoT Hub.
getBodyfunctionMANDATORYCallback for retrieving the body 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.
endpointstring/messages/events?api-version=2018-06-30A valid Azure IoT Hub Routing endpoint. QoS and other properties are query parameters, described as {property_bag} in the Azure IoT Documentation. By default, this POSTs to the telemetry endpoint /messages/events?api-version=2018-06-30.
returnundefined--

Responses

This library uses an object to handle Azure IoT Hub 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 HTTPS response data.

Errors

This library passes an Error object from HTTPS 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 HTTPS request.

NameTypeDefaultSummary
returnundefined--

.mqttConnect(token[,options])

Establish a connection with Azure IoT Hub following the MQTT connection documentation. Azure IoT Hub only supports one active MQTT connection per device.

Before use, ensure the proper permissions are set and that connecting this device is allowed within IoT Hub limits.

Authentication using x.509 certificates is not currently supported.

NameTypeDefaultSummary
tokenstringMANDATORYThe token used for authentication, returned from generateSasToken
optionsobject{}The MQTT Options from the appropriate MQTT documentation. clientId, username, and password are reserved and will be overwritten.
returnMQTT.Client-An MQTT Client connected to Azure IoT Hub. See the device's appropriate MQTT page for more details on this object.
- NEQTO Bridge
- Spresense

Object Usage Examples

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

/* Baltimore CyberTrust Root Certificate -- 653b494a */
var rootCa = "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\nRTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\nVQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\nDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\nZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\nVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\nmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\nIZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\nmpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\nXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\ndc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\njl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\nBE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\nDQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\njkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\nEpn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\nksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\nR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n-----END CERTIFICATE-----\n"

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

The following sample code sections all use the following configuration:

// IMPORTED LIBRARIES
// - Azure_IoT_V2

// Setup logging
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

// Set config
var config = {
    host: "<String>",
    deviceId: "<String>",
    primaryKey: "<String>",
    tokenTimeout: "<Number>",
    timeout: "<Number>",
    ca: rootCa
};

var iot = new AZURE_IOT(config);

if ('errors' in iot) {
    // TODO: Handle errors
    throw 'Invalid configuration'
}

Sample 1: Basic HTTPS Communication

var token = iot.generateSasToken();
var body = "sample text to send to Azure IoT Hub"
var getBody = function() {
    var temp = body;
    body = null;
    return temp;
}
var length = body.length.toString();

var callback = function (err, data) {
    if (err) {
        print("Error!", err.errCode, err.message);
    } else {
        print(data.statusCode, data.statusMessage);
        print(data.body);
    }
}
iot.httpPost(token, length, getBody, callback);

Sample 2: Using MQTT with Token Refresh

var reconnectAttempts = 0;
var client;

var reconnectSt = 0;    //0: No reconnect, 1: Reconnect backoff, 2: Expired backoff(available reconnect)
var scheduleMqttReconnect = function() {
    if(reconnectSt) {
        return;
    }
    reconnectSt = 1;    // Waiting reconnect
    var backoff = 64 * 1000;    //backoff[msec]
    reconnectAttempts++;
    if(client) {
        client.end(); // close the connection, free resources
        client = undefined; // destroy the current client
    }
    print('Reconnect backoff[ms]:' + backoff);
    setTimeout(function() {
        print('Backoff expired');
        reconnectSt=2;
    }, backoff);
}

var registerEventHandlers = function() {
    if(!client){
        print('skip registerEventHandlers()');
        return; // quit
    }
    client.on('connect', function() {
        reconnectAttempts = 0;
        if(client.isConnected()){
            client.subscribe(`devices/${config.deviceId}/messages/devicebound/#`, { 'qos' : 1 }, function(err) {
                if(err.code != 0){
                    print('subscribe() failed');
                    //TODO: Error Handling. (Reconnect is recommended)
                }
            });
        }
    });
    client.on('error', function(err) {
        print('mqttClientOnError: ' + err.code);
        if(err.code == 1) {     // 1: connection failed
            var errnoConnect = client.get('errnoConnect');
            print('errnoConnect ' + errnoConnect);
            scheduleMqttReconnect();
        } else {
            //TODO: Error Handling.
        }
    });
    client.on('message', function(topic, message) {
        print('TOPIC ' + topic);
        print('MESSAGE ' + message);
        //TODO: Message Handling
    });
    client.on('close', function() {
        print('DISCONNECTED');
        scheduleMqttReconnect();
    });
}

var publishInterval = 60 * 1000;
var publishEvent = 0;
setInterval(function() {
    publishEvent = 1;
}, publishInterval);

//  Main loop
reconnectSt = 2;
while(1) {
    if(reconnectSt == 2) {  //Allow MQTT connection
        reconnectSt = 0;
        if(!client) {
            var token = iot.generateSasToken();  //update JWT each connection. default == 1 hour.
            client = iot.mqttConnect(token);
            if(!client) {
                scheduleMqttReconnect();
            } else {
                registerEventHandlers();
            }
        } else {
            client.reconnect();
        }
    }
    if(client && client.canPublish()) {
        if(publishEvent) {
            publishEvent = 0;
            client.publish(`devices/${config.deviceId}/messages/events/?api-version=2018-06-30`, 'Publishing over MQTT', { 'qos' : 1 }, function(err) {
                if(err.code == 0) {
                    print('publish success');
                } else {
                    print('publish failure ' + err.code);
                }
            });
        }
    }
}
The company names and product names mentioned above are registered trademarks or trademarks of their respective companies.

Updated: 2021-03-30
← AWS S3 v2 LibraryGCP IoT Core Library →
  • Abstracts
    • {AZURE_IOT} Instance
  • Details
    • new AZURE_IOT(config)
    • Setter Methods
    • Instance Methods
  • Object Usage Examples
    • Sample 1: Basic HTTPS Communication
    • Sample 2: Using MQTT with Token Refresh
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.