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 | 2.1.0 |
Code size used | 4.1KB |
Resources used | HTTPS x 1, MQTT x 1, Timers x 1 |
Related Documents
- For detailed specifications regarding Azure IoT Hub, please refer to the "Azure IoT Hub Documentation".
- Specification of the HTTPS object (
NEQTO Bridge
/STM32 Discovery
/SPRESENSE
/Linux
) - Specification of the MQTT object (
NEQTO Bridge
/STM32 Discovery
/SPRESENSE
/Linux
)
Limitations
- This library only supports device authentication with
Shared Access Signature (SAS) tokens
.
Device authentication using thex.509 certificate
is not supported.
Abstracts
Methods()/Properties | Summary | Note |
---|---|---|
new AZURE_IOT() | Creates an AZURE_IOT instance. |
{AZURE_IOT} Instance
Methods()/Properties | Summary | Note |
---|---|---|
.generateSasToken() | Generates a SAS token. | |
.httpPost() | Sends data to Azure IoT Hub via HTTPS. | |
.abortHttpRequest() | Aborts the currently ongoing HTTP request. | |
.mqttConnect() | Connects to Azure IoT Hub with MQTT. | |
.errors | Array containing invalid key names (string) Generated when an invalid parameter is detected in the constructor or .setConfig(). | |
.CONST.VERSION | Version (string) | v2.1.0+ |
Details
new AZURE_IOT([config])
Creates an AZURE_IOT instance.
Name | Type | M/O | Description | Note |
---|---|---|---|---|
config | Object | optional | Configuration Refer to config for details. | |
return | {AZURE_IOT} | - | {AZURE_IOT} : Generated {AZURE_IOT} | If invalid parameters are detected, .errors will be generated. |
config
Name | Type | M/O | Description | Note |
---|---|---|---|---|
host | string | mandatory | An Azure IoT Hub endpoint By default, the DNS name of Azure IoT Hub looks like {IoT Hub name}.azure-devices.net . | |
deviceId | string | mandatory | Device ID This is created when a device is registered to the identity registry in Azure IoT Hub. | |
primaryKey | string | mandatory | Service Primary Key Specify a symmetric device key or a shared access key in the identity registry. | |
ca | string | mandatory | Root CA certificate for Azure IoT Hub Specify a string in PEM format. Use \n for line feed code. | |
tokenTimeout | number | optional | SAS token timeout value [s] Specify the period during which the generated SAS tokens will be valid. The default value is 3600 . | |
httpTimeout | number | optional | HTTP request timeout value [s] If 0 , the timeout function is disabled.The default value is 0 . | v2.1.0+ |
timeout | number | - | This parameter is ignored. | Unused |
Set the Configuration (config) when creating an AZURE_IOT instance.
If an invalid parameter is detected, an array containing the name of the invalid keys is generated as the .errors property. If the parameters are successful, the .errors property will be deleted.
var iot = new AZURE_IOT({
host: <value>,
deviceId: <value>,
primaryKey: <value>,
ca: <value>,
tokenTimeout: <value>
});
if('errors' in iot) {
//TODO: Handle errors
}
.setConfig(config)
Set the Configuration (config) after the AZURE_IOT instance is created.
If an invalid parameter is detected, an array containing the name of the invalid keys is generated as the .errors property. If the parameters are successful, the .errors property will be deleted.
var iot = new AZURE_IOT();
iot.setConfig({
host: <value>,
deviceId: <value>,
primaryKey: <value>,
ca: <value>,
tokenTimeout: <value>
});
if('errors' in iot) {
//TODO: Handle errors
}
Setter Methods
After the AZURE_IOT instance is created, Configuration (config) can be set individually using the following setter methods.
If successful, the own instance is returned. If an invalid parameter is detected, false
is returned.
Setter Method | Description | Note |
---|---|---|
.setHost(value) | Sets the host . | |
.setDeviceId(value) | Sets the deviceId . | |
.setPrimaryKey(value) | Sets the primaryKey . | |
.setRootCA(value) | Sets the ca . | |
.setTokenTimeout(value) | Sets the tokenTimeout . | |
.setHttpTimeout(value) | Sets the httpTimeout . | v2.1.0+ |
.setTimeout(value) | Sets the timeout . | Unused |
.generateSasToken([[[[resourceUri],signingKey],policyName],expiresInSecs])
Generates a SAS token.
Name | Type | M/O | Description | Note |
---|---|---|---|---|
resourceUri | string | optional | Specify the URI prefix of the endpoint. The default value is ${config.host}/devices/${config.deviceId} . | |
signingKey | string | optional | Specify the signature key for the SAS token. The default value is config.primaryKey . | |
policyName | string | optional | Specify the shared access policy name. Only if specified, the authorization rule name is added to the SAS token. The default value is undefined . | |
expiresInSecs | number | optional | Specify the token timeout value [s]. The expiration time of the token is the time this method is called, added to this timeout value. The default value is config.tokenTimeout . | |
return | string | - | Authentication token used to establish HTTPS requests or MQTT connections |
.httpPost(token,length,getBody,callback[[,endpoint],sockTo])
Sends data to Azure IoT Hub via HTTPS.
Name | Type | M/O | Description | Note |
---|---|---|---|---|
token | string | mandatory | Specify the authentication token generated by the .generateSasToken() method. | |
length | number | mandatory | Specify the size of the data (body ) to be sent. | |
getBody | function | mandatory | Execute callback processing at the timing when this method will accept the data (body ) to be sent.Returns data in string or ArrayBuffer chunks of 4KB or less until there is no more data, and finally returns null . | |
callback(err, resp) | function | mandatory | Execute callback processing when this method is completed. Notify the processing result using the argument of the callback function. err: {HttpReqError}, null resp: {HttpResponse}, null If an error occurs in the HTTP request, err is set; if an HTTP response could be received, resp is set. | |
endpoint | string | optional | Specify the routing endpoint. The default value is /devices/${config.deviceId}/messages/events?api-version=2018-06-30 . | |
sockTo | number | optional | Specify the HTTP session timeout value [ms]. This parameter is the sockTo setting value of the https.request() method. For details, refer to the HTTPS object specification. | v2.1.0+ |
return | undefined | - |
{HttpReqError}
Name | Type | Description | Note |
---|---|---|---|
.errCode | number | The error code of the HTTPS request For details, refer to the error code table of the HTTPS object. |
{HttpResponse}
Name | Type | Description | Note |
---|---|---|---|
.statusCode | number | The status code of the HTTP response | |
.statusMessage | string | The status message of the HTTP response | |
.body | string, null | HTTP response data (Response-Body ) |
.abortHttpRequest()
Aborts the currently ongoing HTTP request.
Name | Type | M/O | Description | Note |
---|---|---|---|---|
return | undefined | - |
.mqttConnect(token[,options])
Connects to Azure IoT Hub with MQTT.
This method is a wrapper function for the mqtt.connect()
method.
Create an MQTT client instance {Client}
for MQTT connection to Azure IoT Hub.
Refer to MQTT object specification for information on how to use the generated {Client}
instance.
Name | Type | M/O | Description | Note |
---|---|---|---|---|
token | string | mandatory | Specify the authentication token generated by the .generateSasToken() method. | |
options | object | optional | This parameter is the options setting of the mqtt.connect() method. For details, refer to the MQTT object specification.Note that some parameters are overridden by this method. | |
return | {Client}, undefined | - | MQTT client instance for Azure IoT Hub |
mqtt.connect()
that are overridden by this method:
Configuration values related to - mqtt.set(’ssl.ca’, certificate)
- certificate:
config.ca
- certificate:
- mqtt.connect(url[, options])
- url:
mqtts://${config.host}:8883
- options.clientId:
config.deviceId
- options.username:
${config.host}/${config.deviceId}/?api-version=2018-06-30
- options.password:
token
- url:
Usage Examples
The following common code is used in all sample code:
Make sure that the root CA certificate is appropriate for the Azure IoT Hub endpoint in advance.
For information on how to obtain a CA certificate, please refer to here.
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
var rootCa = '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----';
//TODO: Configuration
var config = {
host: <value>,
deviceId: <value>,
primaryKey: <value>,
ca: rootCa,
tokenTimeout: <value>
};
var iot = new AZURE_IOT(config);
if('errors' in iot) {
//TODO: Handle errors
throw new Error("Invalid configuration");
}
Sample 1
Send data to Azure IoT Hub via HTTPS.
var token = iot.generateSasToken();
var body = "sample text to send to Azure IoT Hub";
var busy;
var getBody = function() {
var temp = body;
body = null;
return temp;
};
var callback = function(err, resp) {
if(err) {
print("Error!", err.errCode);
} else {
print("Response:", resp.body);
print("Status:", resp.statusCode, resp.statusMessage);
}
busy = false;
};
busy = true;
iot.httpPost(token, body.length, getBody, callback);
while(busy);
print("Done");
Sample 2
Send data in chunks to Azure IoT Hub via HTTPS.
var token = iot.generateSasToken();
var body = "sample text to send to Azure IoT Hub[...]";
var busy;
var chunkSize = 8; //4KB or less
var index = 0;
var getBody = function() {
var chunk = body.substring(index, index + chunkSize);
if(chunk) {
index = index + chunkSize;
return chunk;
}
return null;
};
var callback = function(err, resp) {
if(err) {
print("Error!", err.errCode);
} else {
print("Response:", resp.body);
print("Status:", resp.statusCode, resp.statusMessage);
}
busy = false;
};
busy = true;
iot.httpPost(token, body.length, getBody, callback);
while(busy);
print("Done");
Sample 3
Connect to Azure IoT Hub with MQTT.
When the MQTT connection is disconnected, update the token and reconnect MQTT.
var mqttConnect = function(onConnected, onDisconnected) {
var token = iot.generateSasToken(); //Update token
print(token);
var cli = iot.mqttConnect(token);
if(!cli) return undefined;
cli.on('error', function(err) {
//TODO: Handle errors
print("Error!", err.code, `(${cli.get('errnoConnect')})`);
if(err.code == 1 && onDisconnected) { //Connection failed
onDisconnected();
return;
}
});
cli.on('message', function(topic, message) {
//TODO: Handle messages
print("Message:", `[${topic}]`, message);
});
cli.on('close', function() {
print("DISCONNECTED");
if(onDisconnected) {
onDisconnected();
}
});
cli.on('connect', function() {
print("CONNECTED");
if(onConnected) {
onConnected();
}
});
return cli;
};
var onMqttConnect = function() {
client.subscribe(`devices/${config.deviceId}/messages/devicebound/#`, {qos: 1}, function(err) {
if(err.code != 0) {
//TODO: Handle errors
print("Subscribe Error!", err.code);
}
});
};
var onMqttDisconnect = function() {
if(client) client.end();
client = undefined;
setTimeout(function() {
print("Reconnecting...");
client = mqttConnect(onMqttConnect, onMqttDisconnect);
if(!client) {
onMqttDisconnect();
}
}, 10000);
};
var client = mqttConnect(onMqttConnect, onMqttDisconnect);
if(!client) {
throw new Error("Failed to create mqtt instance");
}
var publishInterval = 5 * 1000;
var publishEvent = false;
var publishCnt = 0;
setInterval(function() {
publishEvent = true;
}, publishInterval);
while(1) {
if(client && client.canPublish() && publishEvent) {
publishEvent = undefined;
publishCnt++;
var message = JSON.stringify({"message" : "publish" + publishCnt});
client.publish(`devices/${config.deviceId}/messages/events/?api-version=2018-06-30`, message, {qos: 1}, function(err) {
if(err.code == 0) {
print("Publish OK");
} else {
//TODO: Handle errors
print("Publish failed");
}
});
}
}