Niagara
このスニペットは、NiagaraにIoTデータを送信する機能を提供します。
Resources used: HTTPS x 1
or MQTTS x 1
oBIXまたはMQTTを使用してNiagaraホストとNEQTO デバイスを動作させるための設定については、こちらのブログ記事を参照してください。
Details
send_niagara
関数を使用して、HTTPS経由でNiagara oBIXサーバーに返された「ペイロード」をPOSTできます。 次に、結果(エラー/応答)がコールバック関数に返されます。
このスニペットを使用するには、 HOST
(oBIXサーバー/MQTTブローカーのインスタンスの住所)、 PORT
(oBIXサーバー/MQTTブローカーのポート)、 PATH
(oBIXサーバーの場合、データを書き込む要素のパス)、 USERNAME
、 PASSWORD
と CA
をユーザーが設定する必要があります。
注意: 提供されている関数では、最大4KBまでのデータを取り扱うことができます。より大きなサイズのデータを取り扱う場合は、neqto.jsドキュメントのhttpsオブジェクト、分割書き込みを参考にしてください。
HTTPS (oBIX)
//=================================================================
// NIAGARA OBIX SAMPLE CODE
//=================================================================
//=================================================================
// The following configuration are MANDATORY. Set by user.
//=================================================================
// The address of the oBIX Server.
var HOST = '<YOUR_HOST>';
// The port of the oBIX Server.
var PORT = '<YOUR_PORT>';
// The path to make requests to.
var PATH = '<YOUR_PATH>';
// The Username for authorization.
var USERNAME = '<YOUR_USERNAME>';
// The Password for authorization.
var PASSWORD = '<YOUR_PASSWORD>';
// Public certificate of the certificate authority that signed the oBIX server certificate for SSL/TLS handshake.
// eg. '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----'
var CA = '<YOUR_CA>';
//=================================================================
/**
* Post data to Niagara oBIX server using basic authentication.
* @function send_niagara
* @param {string} payload - The data to be sent to Niagara, as a string.
* @param {function} callback - User callback to return the result (error/response).
* @returns {undefined}
*/
var send_niagara = function (payload, callback) {
var body = `<real val='${payload}'/>`; // assuming it is a string writable path
var options = {
"method": 'POST',
"host": HOST,
"port": Number(PORT),
"path": PATH,
"headers": {
"Authorization": 'Basic ' + secure.base64Encode(`${USERNAME}:${PASSWORD}`),
"Content-Type": 'application/json',
"Content-Length": body.length.toString()
},
"ca": CA
};
var request = https.request(options, function (res) {
res.on('readable', function () {
callback(null, { "statusCode": res.statusCode, "statusMessage": res.statusMessage, "body": res.read() });
});
res.on('end', function () {
callback(null, { "statusCode": res.statusCode, "statusMessage": res.statusMessage, "body": res.read() });
});
});
request.on('error', function () {
callback({ "errCode": request.errCode }, null);
});
request.end(body.toString(), function () {
print('[request] SUCCESS');
});
}
MQTTS
//=================================================================
// NIAGARA MQTT SAMPLE CODE
//=================================================================
//=================================================================
// The following configuration are MANDATORY. Set by user.
//=================================================================
// The address of the MQTT Broker.
var HOST = '<YOUR_HOST>';
// The port of the MQTT Broker.
var PORT = '<YOUR_PORT>';
// The Username for authorization.
var USERNAME = '<YOUR_USERNAME>';
// The Password for authorization.
var PASSWORD = '<YOUR_PASSWORD>';
// Public certificate of the certificate authority that signed the MQTT broker certificate for SSL/TLS handshake.
// eg. '-----BEGIN CERTIFICATE-----\n...<CA>...\n-----END CERTIFICATE-----'
var CA = '<YOUR_CA>';
//=================================================================
/**
* Create an MQTT Client connected to the specified MQTT Broker using basic authentication.
* @function mqtt_niagara
* @param {object} options - MQTT Configuration for connecting to the broker, as an Object.
* @returns {(Client|undefined)} - {Client} : Generated MQTT {Client} | undefined : {Client} generate failed due to invalid arguments or insufficient resources.
*/
var mqtt_niagara = function (options) {
mqtt.set('ssl.ca', CA);
return mqtt.connect(`mqtts://${HOST}:${PORT}`, options);
}
Function Usage Example
Sample 1
これはsend_niagara
関数を使用してサーバへデータを送信するサンプルです。
/*
<INSERT ABOVE SNIPPET HERE WITH SET CONFIGURATIONS>
*/
//=================================================================
log.setLevel(-1); //-1:NONE 0:ERROR 1:WARNING 2:DEBUG 3:TRACE
log.printLevel(2); //0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
//=================================================================
// MAIN SCENARIO
//=================================================================
/**
* Callback to fetch error/response from the request.
* @function callback
* @param {object} err - Error returned in case of a failed request. Has one property - `errCode`.
* @param {object} data - Response returned by a successfully completed request. Has three properties - `statusCode`, `statusMessage`, and `body`.
*/
var callback = function (err, data) {
if (err) {
print("[error]", err.errCode);
} else {
print("[status]", data.statusCode, data.statusMessage);
print("[response]", data.body);
}
}
var payload = "Hello from NEQTO Device";
send_niagara(payload, callback);
Sample 2
これは自動再接続を有効にして、mqtt_niagara
関数から返されたクライアントでパブリッシュおよびサブスクライブするサンプルです。 接続後に送受信のループバックテストを行います。
/*
<INSERT ABOVE SNIPPET HERE WITH SET CONFIGURATIONS>
*/
//=================================================================
log.setLevel(-1); //-1:NONE 0:ERROR 1:WARNING 2:DEBUG 3:TRACE
log.printLevel(2); //0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
//=================================================================
// MAIN SCENARIO
//=================================================================
var sub_topic = 'niagara/test/sub';
var pub_topic = 'niagara/test/pub';
var client = mqtt_niagara({
"username": USERNAME, // MANDATORY
"password": PASSWORD, // MANDATORY
"reconnectCount": 1855
});
if (!client) {
throw 'Failed to create mqtt instance';
}
var registerEventHandlers = function () {
if (!client) {
return;
}
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('close', function () {
print("DISCONNECTED");
});
client.on('connect', function () {
print('CONNECTED');
client.subscribe(sub_topic, { qos: 1 }, function (err) {
if (err.code > 0) {
print('MQTT SUBSCRIBE ERROR', err.code);
//TODO: Error handling
}
});
});
};
registerEventHandlers();
setInterval(function () {
if (client.canPublish()) {
var body = 'Hello from NEQTO Device';
client.publish(pub_topic, 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 3
これは手動で再接続して、mqtt_niagara
関数から返されたクライアントでパブリッシュおよびサブスクライブするサンプルです。 再接続が連続して失敗した場合、インスタンスは解放され、再作成されます。
/*
<INSERT ABOVE SNIPPET HERE WITH SET CONFIGURATIONS>
*/
//=================================================================
log.setLevel(-1); //-1:NONE 0:ERROR 1:WARNING 2:DEBUG 3:TRACE
log.printLevel(2); //0:DISABLE 1:LOG 2:CONSOLE 3:BOTH
//=================================================================
// MAIN SCENARIO
//=================================================================
var sub_topic = 'niagara/test/sub';
var pub_topic = 'niagara/test/pub';
var client = mqtt_niagara({
"username": USERNAME, // MANDATORY
"password": PASSWORD // MANDATORY
});
if (!client) {
throw 'Failed to create mqtt instance';
}
var registerEventHandlers = function () {
var reconnectAttempts = 0;
var maxReconnectAttempts = 24;
if (!client) {
return;
}
client.on('error', function (err) {
print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
if (err.code == 1) { //Connection failed
if (reconnectAttempts++ < maxReconnectAttempts) {
print('reconnectAttempts:', reconnectAttempts);
client.reconnect();
} else {
print('ABORT');
reconnectAttempts = 0;
client.end(); //Release mqtt instance
client = undefined;
}
}
});
client.on('message', function (topic, message) {
print('TOPIC: ' + topic + ' MESSAGE: ' + message);
//TODO: Message handling
});
client.on('close', function () {
print("DISCONNECTED");
client.reconnect();
});
client.on('connect', function () {
reconnectAttempts = 0;
print("CONNECTED");
client.subscribe(sub_topic, { qos: 1 }, function (err) {
if (err.code > 0) {
print("MQTT SUBSCRIBE ERROR", err.code);
//TODO: Error handling
}
});
});
};
registerEventHandlers();
setInterval(function () {
if (!client) {
print('Recreating MQTT Instance');
client = mqtt_niagara({
"username": USERNAME, // MANDATORY
"password": PASSWORD // MANDATORY
});
registerEventHandlers();
}
if (client) {
if (client.canPublish()) {
var body = 'Hello from NEQTO Device';
client.publish(pub_topic, body, { qos: 1 }, function (err) {
if (err.code == 0) {
print('Publish OK');
} else {
print('Publish Failed');
//TODO: Error handling
}
});
}
} else {
print('Cannot Publish');
}
}, 15000);
上記に記載されている会社名、製品名は、各社の登録商標または商標です。
Updated: 2021-12-13