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

›Integration

Getting Started

  • NEQTO Hello World!
  • Tutorial Step 1. NEQTO Console Setting
  • Tutorial Step 2. Device Settings & Launching Service (NEQTO Bridge)
  • Tutorial Step 2. Device Settings & Launching Service (STM32 Discovery)
  • Tutorial Step 2. Device Settings & Launching Service (SPRESENSE)
  • Tutorial Step 3. Application development using scripts

NEQTO

  • NEQTO Account Registration
  • Sub-accounts
  • API Usage
  • NEQTO CloudSync for GCP
  • NEQTO Engine Firmware List
  • Support Guidelines

NEQTO Console

  • Introduction
  • Fundamentals
  • Administrative Actions
  • Device Management
  • Linux-based Device Management
  • Batch Registration
  • Scripts
  • Actions and Contacts
  • View Data from the Console
  • NEQTO Apps

    • About NEQTO Apps
    • NEQTO Infinitypool
    • NEQTO Insights
    • NEQTO Custodia
    • NEQTO Flow
  • 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
    • 04. Spresense LTE-M 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
    • 09. Sleep
    • 10. RTC
    • 11. GPIO
    • 12. UART
    • 13. SPI
    • 14. I2C
    • 15. ADC
    • 16. GNSS
    • 17. Camera
    • 18. Utils
    • 19. nqSpresense
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi
    • 24. nqLte

STM32 Discovery

    Hardware Specifications

    • 01. About STM32 Discovery Kit (B-L4S5I-IOT01A)

    Software Specifications

    • 01. Operational Flow
    • 02. Initial Installation
    • 03. STM32 Discovery Wi-Fi 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
    • 18. Utils
    • 19. nqDiscovery
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi

NEQTO Bridge

    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
    • 07. NEQTO Bridge Connector 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. Utils
    • 19. nqBridge
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi
    • 24. nqLte
    • 25. nqLAN
    • 26. nqEx

Linux-based device

    Software Specifications

    • 01. System Requirements
    • 02. Installation
    • 03. Software Configurations
    • 04. Operational Flow
    • 05. Debug Log Acquisition
    • 06. Event Messages
    • 07. Updating Software

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. RTC
    • 10. UNIXSocket
    • 11. FileSystem
    • 12. SubProcess
    • 13. Utils
    • 14. nqLinux
    • 15. nqService
    • 16. nqMqtt
    • 17. nqFOTA
    • 18. nqLAN

neqto.js Libraries

  • About neqto.js Libraries
  • UART

    • GM65 Barcode Reader
    • SRF Ultrasonic Range Finder - Serial Mode

    I2C

    • HTS221 v2 Temperature and Humidity Sensor
    • LIS2DW12 v2 Accelerometer
    • SRF Ultrasonic Range Finder - I2C Mode
    • [Archive] HTS221 Temperature and Humidity Sensor
    • [Archive] LIS2DW12 Accelerometer

    Utils

    • RTC Alarm Synchronized Scheduler

    Integration

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

neqto.js Snippets

  • About neqto.js Snippets
  • DataDog
  • Dropbox
  • Google Sheets
  • InfluxDB
  • Oracle Cloud Object Storage
  • Salesforce
  • SAP Cloud Platform Internet of Things
  • Splunk
  • Niagara

Release Notes

  • NEQTO Console Updates
  • NEQTO Firmware (Bridge Wi-Fi/LTE Module) Releases
  • NEQTO Firmware (STM32 Discovery Wi-Fi) Releases
  • NEQTO Firmware (Spresense Wi-Fi/LTE-M) Releases
  • NEQTO Engine for Linux Releases

Azure IoT v2

This library is a built-in class that provides functions to communicate with Azure IoT Hub.

Library usage requirements
Type Integrations
Name Azure_IoT_V2
Version 2020-11-04
Code size used 2.8KB
Resources used HTTPS x 1, MQTT x 1, Timers x 1

Related Documents

For information on the Azure IoT Hub API used in this library, please refer to the documentation.



Abstracts

Methods()/PropertiesSummary
new AZURE_IOT()Initializes the AZURE_IOT instance with the passed configuration.

{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

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 Azure IoT Hub endpoint.

var rootCa = '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----';

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: 2023-01-20
← AWS IoT Core v2GCP IoT Core →
  • Abstracts
    • {AZURE_IOT} Instance
  • Details
    • new AZURE_IOT(config)
    • Setter Methods
    • Instance Methods
  • 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
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.
© 2023 JIG-SAW INC.