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()/Properties | Summary |
---|---|
new AZURE_IOT() | Initializes the AZURE_IOT instance with the passed configuration. |
{AZURE_IOT} Instance
Methods()/Properties | Summary |
---|---|
.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. |
.errors | An 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:
Name | Type | Default | Summary |
---|---|---|---|
host | string | MANDATORY | A valid Azure IoT Hub endpoint; By default, the DNS name of an Azure IoT hub looks like {IoT Hub name}.azure-devices.net . |
deviceId | string | MANDATORY | The device ID in Azure IoT Hub. This is created when a device is registered to the identity registry in Azure IoT Hub. |
primaryKey | string | MANDATORY | The 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. |
ca | string | MANDATORY | The root CA for HTTP requests made by this instance. |
timeout | number | 90000 | Defaults to 90000 milliseconds (90s). For HTTPS requests, changes the time before a request automatically times out. |
tokenTimeout | number | 3600 | Defaults 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
.
Setter | Summary |
---|---|
.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.
Name | Type | Default | Summary |
---|---|---|---|
resourceUri | string | {host}/devices/{deviceId} | The URI for this device. |
signingKey | string | {primaryKey} | The key used for signing the SAS token. |
policyName | string | undefined | The 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. |
expiresInSecs | string | tokenTimeout | The token timeout. |
return | string | - | 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.
Name | Type | Default | Summary |
---|---|---|---|
token | string | MANDATORY | The token used for authentication, returned from generateSasToken |
length | number | MANDATORY | Total amount of data to send to Azure IoT Hub. |
getBody | function | MANDATORY | Callback 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) | function | MANDATORY | The user's callback function, to handle the response. Will pass an Error as err and a Response as resp . |
endpoint | string | /messages/events?api-version=2018-06-30 | A 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 . |
return | undefined | - | - |
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.
Name | Type | Default | Summary |
---|---|---|---|
return | undefined | - | - |
.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.
Name | Type | Default | Summary |
---|---|---|---|
token | string | MANDATORY | The token used for authentication, returned from generateSasToken |
options | object | {} | The MQTT Options from the appropriate MQTT documentation. clientId , username , and password are reserved and will be overwritten. |
return | MQTT.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);
}
});
}
}
}