From b455e070e10a9ed46db3c7767bd911d138339b8f Mon Sep 17 00:00:00 2001 From: sw-iot-sagarvaghela Date: Fri, 16 Feb 2024 11:11:42 +0530 Subject: [PATCH] Initial Commit --- .gitignore | 3 + README.md | 60 +- iotconnect-sdk/README.md | 270 +++-- iotconnect-sdk/app.js | 6 - iotconnect-sdk/client/azClient.js | 384 ------- iotconnect-sdk/client/mqttClient.js | 329 +++--- iotconnect-sdk/client/tpmClient.js | 494 --------- iotconnect-sdk/common/common.js | 853 ++++++++++++---- iotconnect-sdk/config/config.js | 29 +- iotconnect-sdk/src/az.js | 1373 -------------------------- iotconnect-sdk/src/mqtt.js | 103 +- iotconnect-sdk/src/tpm.js | 1330 ------------------------- package.json | 10 +- sample/az/example.js | 441 --------- sample/az/firmware.js | 259 ----- sample/example.js | 416 ++++++++ sample/firmware.js | 433 ++++++++ sample/mqtt/example.js | 429 -------- sample/mqtt/example1.js | 430 -------- sample/mqtt/firmware.js | 455 --------- sample/tpm/example.js | 426 -------- sample/tpm/firmware.js | 259 ----- sample/tpm/generateEndorcementKey.js | 29 - 23 files changed, 1922 insertions(+), 6899 deletions(-) create mode 100644 .gitignore delete mode 100644 iotconnect-sdk/client/azClient.js delete mode 100644 iotconnect-sdk/client/tpmClient.js delete mode 100644 iotconnect-sdk/src/az.js delete mode 100644 iotconnect-sdk/src/tpm.js delete mode 100644 sample/az/example.js delete mode 100644 sample/az/firmware.js create mode 100644 sample/example.js create mode 100644 sample/firmware.js delete mode 100644 sample/mqtt/example.js delete mode 100644 sample/mqtt/example1.js delete mode 100644 sample/mqtt/firmware.js delete mode 100644 sample/tpm/example.js delete mode 100644 sample/tpm/firmware.js delete mode 100644 sample/tpm/generateEndorcementKey.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c478ffc --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +.vscode/ +package-lock.json \ No newline at end of file diff --git a/README.md b/README.md index 8af9a06..c7f5a7e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Softweb Solutions Inc -## IOT Connect SDK : Software Development Kit 1.0 Mesage type 2.1 +## IOT Connect SDK : Software Development Kit 2.3.0 **Prerequisite tools:** @@ -8,11 +8,11 @@ **Installation :** -1. Extract the "iotconnect-sdk-node-v1.0.zip" +1. Extract the "iotconnect-sdk-node-v2.3.0.zip" 2. To install the required libraries use the below command: - Goto SDK directory path using terminal/Command prompt - - cd iotconnect-sdk-node-v1.0 + - cd iotconnect-sdk-node-v2.3.0 - npm install (Install prerequisite nodejs library) - npm install iotconnect-sdk (Install the 'iotconnect-sdk' package in nodejs library) @@ -31,15 +31,19 @@ **Usage :** - To initialize the SDK object need to import below sdk package +```node var SDKClient = require('iotconnect-sdk'); +``` - Prerequisite standard input data -- Prerequisite standard configuration data +```node +//"Get your ENV and CPID from the portal key vaults module or visit https://help.iotconnect.io SDK section." +var uniqueId = <>; +var cpId = <>; +var env = <>; ``` -UniqueId = "<>" -SId = "<>" - - SdkOptions is for the SDK configuration and need to parse in SDK object initialize call. You need to manage the below onfiguration as per your device authentications. +```json var sdkOptions = { "certificate" : { //For SSL CA signed and SelfSigned authorized device only "SSLKeyPath" : "<< SystemPath >>/device.key", @@ -62,33 +66,44 @@ Note: sdkOptions is a mandatory parameter for sdk object initialize call. - disabled : false = offline data storing, true = not storing offline data - availSpaceInMb : Define the file size of offline data which should be in (MB) - fileCount : Number of files need to create for offline data - "discoveryUrl" : (*) Discovery URL is mandatory parameter to get device details +``` - To Initialize the SDK object and connect to the cloud +```node var iotConnectSDK = new SDKClient(cpid, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); - Note : sdkOptions is an optional parameter +``` - To receive the command from Cloud to Device(C2D) +```node var deviceCallback = function deviceCallback(data){ console.log(data); if(data.cmdType == "0x01") // Device Command if(data.cmdType == "0x02") // Firmware Command + if(data.cmdType == "0x16") + // Device connection status } +``` - To receive the twin from Cloud to Device(C2D) +```node var twinUpdateCallback = function twinUpdateCallback(data){ console.log(data); } +``` - To get the list of attributes +```node iotConnectSDK.getAttributes(function(response){ console.log("Attributed :: "+ response); }); +``` - This is the standard data input format for Gateway and non Gateway device. +```json 1. For Non Gateway Device var data = [{ "uniqueId": "<< Device UniqueId >>", @@ -107,11 +122,15 @@ var data = [{ "time": "<< date >>", // "2019-12-24T10:06:17.857Z" Date format should be as defined "data": {} // example : {"temperature": 15.55, "gyroscope" : { 'x' : -1.2 }} }] +``` - To send the data from Device To Cloud(D2C) +```node iotConnectSDK.sendData(data); +``` - To send the command acknowledgment +```node var obj = { "ackId": data.ackId, "st": Acknowledgment status sent to cloud @@ -133,20 +152,27 @@ var msgType = 5; // for "0x01" device command var msgType = 11; // for "0x02" Firmware OTA command iotConnectSDK.sendAck(obj, msgType) +``` - To update the Twin Property +```node var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message var value = "<< Desired Property value >>"; // Value of respective desired property Example : var key = "firmware_version"; var value = "4.0"; iotConnectSDK.updateTwin(key,value) +``` - To disconnect the device from the cloud +```node iotConnectSDK.dispose() +``` - To get the all twin property Desired and Reported +```node iotConnectSDK.getAllTwins(); +``` ## Release Note : @@ -166,4 +192,20 @@ iotConnectSDK.getAllTwins(); ** Improvements ** 1. We have updated below methods name: To Initialize the SDK object: - - new SDKClient(uniqueId, sId, sdkOptions, function(response) \ No newline at end of file + - Old : new sdk(cpid, uniqueId, callbackMessage, twinCallbackMessage, env, sdkOptions); + - New : new SDKClient(cpid, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); + To send the data : + - Old : SendData(data) + - New : sendData(data) + To update the Twin Reported Property : + - Old : UpdateTwin(key, value) + - New : updateTwin(key, value) + To receive Device command callback : + - Old : callbackMessage(data); + - New : deviceCallback(data); + To receive OTA command callback : + - Old : twinCallbackMessage(data); + - New : twinUpdateCallback(data); +2. Remove properties.json file and use the sdkOptions for the certificate and offline data storage configuration. +3. Discovery URL moves from hard code setting to the sdkOptions to enhance the global experience. +4. Update the OTA command recceiveer payload for multiple OTA files \ No newline at end of file diff --git a/iotconnect-sdk/README.md b/iotconnect-sdk/README.md index 8af9a06..a42488c 100644 --- a/iotconnect-sdk/README.md +++ b/iotconnect-sdk/README.md @@ -1,102 +1,197 @@ # Softweb Solutions Inc -## IOT Connect SDK : Software Development Kit 1.0 Mesage type 2.1 + +## IOT Connect SDK : Software Development Kit 1.0 **Prerequisite tools:** 1. NodeJs : Node.js supported version v8.x and above -2. Npm : NPM is compatible with the node version +2. Npm : NPM compatible with the node version + +**Installation :** -**Installation :** +1. Clone this repository +2. Navigate to this directory using terminal or command prompt +3. To install the required libraries use the below command: -1. Extract the "iotconnect-sdk-node-v1.0.zip" + ``` + cd iotc-node-sdk + npm install + ``` +4. Open firmware.js or example.js file from folder named sample and update the following details -2. To install the required libraries use the below command: - - Goto SDK directory path using terminal/Command prompt - - cd iotconnect-sdk-node-v1.0 - - npm install (Install prerequisite nodejs library) - - npm install iotconnect-sdk (Install the 'iotconnect-sdk' package in nodejs library) + - Prerequisite input data as explained in the usage section as below + - Update sensor attributes according to added in iotconnect cloud platform + - If your device is secure then need to configure the x.509 certificate path as like sdkOptions given below otherwise leave as it is. +5. Using terminal/command prompt goto sample folder -3. Using terminal/command prompt goto sample folder - - cd sample + ```cmd + cd sample + ``` +6. Ready to go: -4. You can take the firmware file from the above location and update the following details - - Prerequisite input data as explained in the usage section as below - - Update sensor attributes according to added in iotconnect cloud platform - - If your device is secure then need to configure the x.509 certificate path as like sdkOptions given below otherwise leave as it is. + ```cmd + node firmware.js // This script send the data on the cloud as per configured device detail + node example.js <> // Command line experience to test the sdk + ``` -5. Ready to go: - - node firmware.js (This script send the data on the cloud as per configured device detail) - - node example.js *<>* (Command line experience to test the sdk) - **Usage :** - To initialize the SDK object need to import below sdk package + +```node var SDKClient = require('iotconnect-sdk'); +``` + +- Prerequisite standard input data -- Prerequisite standard input data -- Prerequisite standard configuration data +```node +//"Get your ENV and CPID from the portal key vaults module or visit https://help.iotconnect.io SDK section." +var uniqueId = "<>"; +var sId ="<>"; +var cpId ="<>"; +var env ="<>"; +var pf ="<>"; ``` -UniqueId = "<>" -SId = "<>" - SdkOptions is for the SDK configuration and need to parse in SDK object initialize call. You need to manage the below onfiguration as per your device authentications. -var sdkOptions = { - "certificate" : { //For SSL CA signed and SelfSigned authorized device only + +```json +{ + "certificate" : { "SSLKeyPath" : "<< SystemPath >>/device.key", - "SSLCertPath" : "<< SystemPath >>/device.pem", - "SSLCaPath" : "<< SystemPath >>/rootCA.pem" - }, + "SSLCertPath" : "<< SystemPath >>/device.pem", + "SSLCaPath" : "<< SystemPath >>/rootCA.pem" + }, "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //size in MB, Default value = unlimted - "fileCount": 5 // Default value = 1 - }, - "discoveryUrl" : "https://discovery.iotconnect.io" // Mandatory parameter to get device details + "disabled": false, + "availSpaceInMb": 1, + "fileCount": 5 + }, + "discoveryUrl" : "", + "debug" : false, + "skipValidation": false, + "cpId" : "", + "env" : "", + "pf": "" } -Note: sdkOptions is a mandatory parameter for sdk object initialize call. - "certificate" : It indicated to define the path of the certificate file. Mandatory for X.509 device CA signed and self-signed authentication type only. - - SSLKeyPath: your device key - - SSLCertPath: your device certificate - - SSLCaPath : Root CA certificate - "offlineStorage" : Define the configuration related to the offline data storage - - disabled : false = offline data storing, true = not storing offline data - - availSpaceInMb : Define the file size of offline data which should be in (MB) - - fileCount : Number of files need to create for offline data - "discoveryUrl" : (*) Discovery URL is mandatory parameter to get device details +``` + +Note: sdkOptions is a mandatory parameter for sdk object initialize call. + +**certificate :** +It indicated to define the path of the certificate file. Mandatory for X.509 device CA signed and self-signed authentication type only. +- SSLKeyPath: your device key +- SSLCertPath: your device certificate +- SSLCaPath : Root CA certificate +- Windows + Linux OS: Use “/” forward slash (Example: Windows: “E:/folder1/folder2/certificate”, +Linux: “/home/folder1/folder2/certificate) + +**offlineStorage :** Define the configuration related to the offline data storage +- disabled : false = offline data storing, true = not storing offline data +- availSpaceInMb : Define the file size of offline data which should be in (MB) +- fileCount : Number of files need to create for offline data + +**discoveryURL (*):** Discovery URL is mandatory parameter to get device details. + +**debug :** Private setting, false(default) = Don't show log, true = Show log + +**skipValidation :** false(default) = Do validation, true = skip validation - To Initialize the SDK object and connect to the cloud -var iotConnectSDK = new SDKClient(cpid, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); -- Note : sdkOptions is an optional parameter +```js +let iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, function(response){ + if(response.status){ + iotConnectSDK.connect(successCallback, failedCallback, connectionStatusCallback) + } else { + // Handle SDK initialization failed here + } +}); +// Set all callbacks after IoTConnectSDK had initialized +initCallbacks(); + +``` + +- To receive the command from Cloud to Device(C2D) + +```js +var deviceCallback = function deviceCallback(data){ + if(data && data.ct == 0 && data.ack) { + // Send Acknowledgement + var ackGuid = data.ack; + var status = 7; // Failed = 4, Executed = 5, Success = 7 + var msg = "Success"; + var childId = data.id ? data.id : null; + iotConnectSDK.sendAckCmd(ackGuid, status, msg, childId); + } else { + // Don't Send Acknowledgement + } +} +``` -- To receive the command from Cloud to Device(C2D) -var deviceCallback = function deviceCallback(data){ - console.log(data); - if(data.cmdType == "0x01") - // Device Command - if(data.cmdType == "0x02") - // Firmware Command +- To receive the OTA command from Cloud to Device(C2D) + +```js +// Callback function to receive OTA command +var receiveOTA = function receiveOTA(data){ + if(data && data.ct == 1 && data.ack) { + // Send Acknowledgement + var ackGuid = data.ack; + var status = 0; + var msg = "Success"; + childGlobal.forEach(c => { + iotConnectSDK.sendAckOTA(ackGuid, status, msg, c); + }) + } else { + // Don't Send Acknowledgement + } } +``` - To receive the twin from Cloud to Device(C2D) + +```js var twinUpdateCallback = function twinUpdateCallback(data){ - console.log(data); + if(data.desired) { + //call updateTwin for every attribute that needs to be updated in cloud. + iotConnectSDK.updateTwin(<>, <>,(response)=>{ + // Handle success or failure of update twin + }) + } } +``` + +- To update the Twin Property Device to Cloud(D2C) -- To get the list of attributes +```js +var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message +var value = "<< Desired Property value >>"; // Value of respective desired property +iotConnectSDK.updateTwin(key,value) +``` + +- To request the list of attributes with the respective device type + +```js iotConnectSDK.getAttributes(function(response){ console.log("Attributed :: "+ response); }); +``` - This is the standard data input format for Gateway and non Gateway device. -1. For Non Gateway Device + +1. For Non Gateway Device + +```js var data = [{ "uniqueId": "<< Device UniqueId >>", - "time" : "<< date >>", //Date format should be as defined + "time" : "<< date >>", // "2019-12-24T10:06:17.857Z" Date format should be as defined "data": {} // example : {"temperature": 15.55, "gyroscope" : { 'x' : -1.2 }} }]; +``` + +2. For Gateway and multiple child device -2. For Gateway and multiple child device +```js var data = [{ "uniqueId": "<< Gateway Device UniqueId >>", // It should be first element "time": "<< date >>", // "2019-12-24T10:06:17.857Z" Date format should be as defined @@ -107,63 +202,22 @@ var data = [{ "time": "<< date >>", // "2019-12-24T10:06:17.857Z" Date format should be as defined "data": {} // example : {"temperature": 15.55, "gyroscope" : { 'x' : -1.2 }} }] +``` - To send the data from Device To Cloud(D2C) -iotConnectSDK.sendData(data); -- To send the command acknowledgment -var obj = { - "ackId": data.ackId, - "st": Acknowledgment status sent to cloud - "msg": "", it is used to send your custom message - "childId": "" it is use for gateway's child device OTA update -} -- ackId(*) : Command ack guid which is receive from command payload -- st(*) : Acknowledgment status sent to cloud (4 = Fail, 6 = Device command[0x01], 7 = Firmware OTA command[0x02]) -- msg : Message -- childId : - 0x01 : null or "" for Device command - 0x02 : null or "" for Gateway device and mandatory for Gateway child device's OTA udoate. - How to get the "childId" .? - - You will get child uniqueId for child device OTA command from payload "data.urls[~].uniqueId" -Note : (*) indicates the mandatory element of the object. - -- Message Type -var msgType = 5; // for "0x01" device command -var msgType = 11; // for "0x02" Firmware OTA command - -iotConnectSDK.sendAck(obj, msgType) - -- To update the Twin Property -var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message -var value = "<< Desired Property value >>"; // Value of respective desired property -Example : -var key = "firmware_version"; -var value = "4.0"; -iotConnectSDK.updateTwin(key,value) +```node +iotConnectSDK.sendData(data); +``` - To disconnect the device from the cloud + +```node iotConnectSDK.dispose() +``` - To get the all twin property Desired and Reported -iotConnectSDK.getAllTwins(); -## Release Note : - -** New Feature ** -1. Offline data storage functionality with specific settings -2. Edge enable device support Gateway device too -3. Device and OTA command acknowledgment -4. It allows to disconnecting the device client -5. Introduce new methods: - sendAck() : to send the command acknowledgement to cloud - dispose() : to disconnect the device - getAllTwins : To receive all the twin properties -6. Support hard stop command from cloud -7. Support OTA command with Gateway and child device -8. It allows sending the OTA command acknowledgment for Gateway and child device - -** Improvements ** -1. We have updated below methods name: - To Initialize the SDK object: - - new SDKClient(uniqueId, sId, sdkOptions, function(response) \ No newline at end of file +```node +iotConnectSDK.getAllTwins(); +``` diff --git a/iotconnect-sdk/app.js b/iotconnect-sdk/app.js index 919eb2f..7bba5ba 100644 --- a/iotconnect-sdk/app.js +++ b/iotconnect-sdk/app.js @@ -1,8 +1,2 @@ -// For IoTConnect TPM authorized SDK -// module.exports = require('./src/tpm'); - -// For IoTConnect Azure based authorized SDK -// module.exports = require('./src/az'); - // For IoTConnect Open source SDK module.exports = require('./src/mqtt'); \ No newline at end of file diff --git a/iotconnect-sdk/client/azClient.js b/iotconnect-sdk/client/azClient.js deleted file mode 100644 index 3ab98a3..0000000 --- a/iotconnect-sdk/client/azClient.js +++ /dev/null @@ -1,384 +0,0 @@ - -var config = require('../config/config'); -var Protocol = require('azure-iot-device-mqtt').Mqtt; -var Client = require('azure-iot-device').Client; -var Message = require('azure-iot-device').Message; -var _ = require('lodash'); - -class AzureClient { - - constructor(sId, uniqueId, sdkOption){ - this.SID = sId; - this.UNIQUEID = uniqueId; - this.CONNECTION_STRING = sdkOption.CONNECTION_STRING; - // console.log("CONNECTION_STRING =.> ", this.CONNECTION_STRING); - this.azClient = "" - } - - // connectCallback() { - // console.log('Client hello connected => ', new Date()); - - - // Create a message and send it to the IoT Hub every two seconds - // sendInterval = setInterval(() => { - // const message = generateMessage(); - // // console.log('Sending message: ' + message.getData()); - // client.sendEvent(message, printResultFor('send')); - // }, 10000); - - // } - - /* - * Azure TPM SDK - * @author : MK - * Create client connection - * @param: - */ - clientConnection(callback) { - var self = this; - try { - - // console.log("Protocol => ", Client); - self.azClient = Client.fromConnectionString(self.CONNECTION_STRING, Protocol); - // Once network connection not vailable then raise the event disconnect and error after defined mili seconds - // console.log("self.azClient => ", self.azClient._maxOperationTimeout); - self.azClient._maxOperationTimeout = 30000; - // self.azClient.on('connect', self.connectCallback); - callback({ - status: true, - data: self.azClient, - message: "Device Connected success fully" - }) - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - * Azure TPM SDK - * @author : MK - * Subscribe the command and twin messages - * @param: uniqueId, cpId - */ - subscribeData(callback) { - try { - var self = this; - let twinCountCall = 0; - if (self.azClient) { - // console.log("self.azClient => ", self.azClient._maxOperationTimeout); - // self.azClient._maxOperationTimeout = 10000; - // console.log("self.azClient => ", self.azClient); - self.azClient.on('connect', function (err) { - console.log("Device connected => ", new Date()); - var deviceCommandAck = { - ct: config.commandType.DEVICE_CONNECTION_STATUS, - uniqueId: self.UNIQUEID, - sid: self.SID, - command: true - } - callback({ - status: true, - data: { - "cmdReceiveType" : "cmd", - "data" : deviceCommandAck - }, - message: "Device connected" - }) - // callback(deviceCommandAck); - }); - self.azClient.on('disconnect', function () { - // self.azClient.removeAllListeners(); - console.log("Device disconnected => ", new Date()); - var deviceCommandAck = { - ct: config.commandType.DEVICE_CONNECTION_STATUS, - uniqueId: self.UNIQUEID, - sid: self.SID, - command: false - // cmdType: config.commandType.DEVICE_CONNECTION_STATUS, - // data: { - // cpid: self.SID, - // guid: '', - // uniqueId: self.UNIQUEID, - // command: false, - // ack: false, - // ackId: '', - // cmdType: config.commandType.DEVICE_CONNECTION_STATUS - // } - } - // self.manageDebugLog("INFO_IN03", uniqueId, cpId, "", 1, isDebug); - callback({ - status: true, - data: { - "cmdReceiveType" : "cmd", - "data" : deviceCommandAck - }, - message: "Device disconnected" - }) - }); - self.azClient.open(function (err) { - if (err) { - callback({ - status: false, - data: null, - message: err.message - }) - } else { - - self.azClient.on('message', function (msg) { - var a = JSON.parse(msg.data); - console.log("Command received => ", JSON.stringify(a)); - // console.log('Id: ' + msg.messageId + ' Body: ' , JSON.parse(msg.data)); - callback({ - status: true, - data: { - "cmdReceiveType" : "cmd", - "data" : JSON.parse(msg.data) - }, - message: "Device command" - }) - }); - // self.azClient.on('error', function (err) { - // console.error(err.message); - // }); - self.azClient.getTwin(function (err, twin) { - self.twinProperty = twin; - if (err) { - callback({ - status: false, - data: err, - message: err.message - }) - } else { - twin.on('properties.desired', function(delta) { - var twinData = {}; - twinData['desired'] = delta; - twinData["uniqueId"] = self.UNIQUEID; - if(twinCountCall == 0){ - twinCountCall++; - } else { - callback({ - status: true, - data: { - "cmdReceiveType" : "twin", - "data" : twinData - }, - message: "All twin message received" - }) - // GLOBAL_CALLBACK_TWIN(twinData); - } - }); - } - }); - } - }); - } else { - callback({ - status: false, - data: error, - message: config.errorLog.ERR_IN11 - }) - } - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - * Azure TPM SDK - * @author : MK - * Publish the message on cloud - * @param: sensorData, uniqueId, cpId - */ - messagePublish(sensorData, callback) { - // console.log("AzureClient -> ============================ -> sensorData", sensorData) - try { - var self = this; - var cd = ""; - var mt = ""; - if(sensorData){ - - mt = sensorData.mt; - if(sensorData.pubTopic) - delete sensorData.pubTopic; - if(sensorData.mt || sensorData.mt == 0){ - if(!_.includes([200, 201, 202, 203, 204, 205, 210, 221, 222], sensorData.mt)) - delete sensorData.mt; - // if(sensorData.mt != 200) - if("sid" in sensorData && sensorData.mt != config.msgType.allStatus) - delete sensorData.sid; // Temp Data - if("v" in sensorData) - delete sensorData.v; - } - if("cd" in sensorData && sensorData.cd) { - cd = sensorData.cd; - delete sensorData.cd; - } - var message = new Message(JSON.stringify(sensorData)); - } - // var tmp = JSON.parse(message); - if(cd) { - message.properties.add("cd", cd ); - } - if(_.includes([200, 201, 202, 203, 204, 205, 210, 221, 222], mt)){ - message.properties.add("di", 1 ); - } else { - message.properties.add("mt", mt ); - } - message.properties.add("v", config.sdkVersion ); - - // message.properties.add("mt", sensorData.mt ); - console.log('Sending message: ' , message.getData() ); - console.log('Sending message: ' , JSON.stringify(message) ); - try { - self.azClient.sendEvent(message, self.printResultFor('send', self.SID + "_" + self.UNIQUEID)); - } catch (error) { - console.log("error -> ", error ); - } - callback({ - status: true, - data: [], - message: "Message published successfully" - }) - } catch (error) { - console.log("error -> ", error ); - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - // Helper function to print results in the console - printResultFor(op, id = "") { - return function printResult(err, res) { - if (err) { - // console.log("\nPublishData ::: " + id + " :: status :: ERROR - " + err.toString() + " :: ", new Date()); - } - if (res) { - if (op == 'send') { - console.log("\nPublishData ::: " + id + " :: status :: " + res.constructor.name + " :: ", new Date()); - } else if (op == 'completed') { - console.log("\nReceivedData ::: " + id + " :: status :: " + res.constructor.name + " :: ", new Date()); - } - } - }; - } - - /* - * Azure TPM SDK - * @author : MK - * Get Twin desired property - * @param: uniqueId, cpId - */ - getTwinProperty(callback) { - try { - var self = this; - self.azClient.getTwin(function (err, twin) { - if (err) { - callback({ - status: false, - data: err, - message: err.message - }) - } else { - callback({ - status: true, - data: null, - message: "Twin message request sent" - }) - } - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - * Azure TPM SDK - * @author : MK - * Update Twin reported property - * @param: data {key: value} - */ - updateTwinProperty(patch, callback) { - try { - var self = this; - var twin = self.twinProperty; - twin.properties.reported.update(patch, function(err) { - if (err) - { - callback({ - status: false, - data: err, - message: err.message - }) - } else { - callback({ - status: true, - data: [], - message: "Twin updated successfully" - }) - } - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - * Azure TPM SDK - * @author : MK - * Disconnect the device - * @param: - */ - disconnect(callback) { - var self = this; - try { - console.log("In client => "); - self.azClient.close(function (err){ - console.log("In client => ", err); - if(err) { - callback({ - status: false, - data: [], - message: err.message - }) - } else { - callback({ - status: true, - data: [], - message: "Client disconnected successfully" - }) - } - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - -} - -module.exports = AzureClient; \ No newline at end of file diff --git a/iotconnect-sdk/client/mqttClient.js b/iotconnect-sdk/client/mqttClient.js index 602147e..d16842c 100644 --- a/iotconnect-sdk/client/mqttClient.js +++ b/iotconnect-sdk/client/mqttClient.js @@ -1,320 +1,234 @@ - -var config = require('../config/config'); -var mqtt = require('mqtt'); -var cache = require('memory-cache'); -var _ = require('lodash'); +var config = require("../config/config"); +var mqtt = require("mqtt"); +var cache = require("memory-cache"); +var _ = require("lodash"); class MqttClient { - - constructor(sId, uniqueId, sdkOption){ - this.clientConnectionConfiguration = ""; - this.mqttClient = ""; + constructor(sId, uniqueId, sdkOption) { + this.clientConnectionConfiguration = ""; + this.mqttClient = ""; this.clientConnectionStatus = false; this.SID = sId; this.UNIQUEID = uniqueId; + this.clientId = ""; this.CONNCALLBACK = uniqueId; this.connectionError = false; this.connectionErrorMessage = ""; + this.sdkOption = sdkOption; } - /* - * MQTT SDK client - * @author : MK - * Create client connection - * @param: mqttUrl, mqttOption - */ + /* + * MQTT SDK client + * @author : MK + * Create client connection + * @param: mqttUrl, mqttOption + */ clientConnection(conObj, callback) { var mqttUrl = conObj.mqttUrl; var mqttOption = conObj.mqttOption; - // console.log("MqttClient -> clientConnection -> mqttOption", mqttUrl) var self = this; - try { - // console.log("else =====", self.mqttClient); - // if(self.mqttClient){ - // self.mqttClient.end(); - // } else { - // console.log("else =====", mqttUrl); - // } + try { + self.clientId = mqttOption.clientId; self.mqttClient = mqtt.connect(mqttUrl, mqttOption); callback({ status: true, data: [], - message: "Device connection process initiated" - }) + message: "Device connection process initiated", + }); } catch (error) { - // console.log("MqttClient -> clientConnection -> error", error) callback({ status: false, data: error, - message: error.message - }) + message: error.message, + }); } } - /* - * Azure TPM SDK - * @author : MK - * Subscribe the command and twin messages - * @param: uniqueId, sId - */ + /* + * + * @author : MK + * Subscribe the command and twin messages + * @param: uniqueId, sId + */ subscribeData(callback) { var self = this; - var cacheId = self.SID+"_"+self.UNIQUEID; + var cacheId = self.SID + "_" + self.UNIQUEID; var deviceSyncRes = cache.get(cacheId); - var twinPropertySubTopic = config.twinPropertySubTopic; - var twinResponseSubTopic = config.twinResponseSubTopic; + var twinPropertySubTopic = config[self.sdkOption.pf]?.twinPropertySubTopic; + var twinResponseSubTopic = config[self.sdkOption.pf]?.twinResponseSubTopic; var brokerConfiguration = deviceSyncRes.p; var deviceSubTopic = brokerConfiguration.topics.c2d; var connectionCnt = 0; - try { - self.mqttClient.on('connect', function () { + if (self.sdkOption.pf === "aws") { + twinPropertySubTopic = deviceSyncRes.p.topics.set.sub; + twinResponseSubTopic = deviceSyncRes.p.topics.set.subForAll; + } + + try { + self.mqttClient.on("connect", function () { self.mqttClient.subscribe(deviceSubTopic); self.mqttClient.subscribe(twinPropertySubTopic); self.mqttClient.subscribe(twinResponseSubTopic); - - // setTimeout(() => { - // var d = { - // "ct": 112, - // "v": 2.1, - // "debugFlag": false - // } - // callback({ - // status: true, - // data: { - // "cmdReceiveType" : "cmd", - // "connectionCnt" : connectionCnt, - // "data" : d - // }, - // message: "Debug flag" - // }) - // }, 50000); - - // setTimeout(() => { - // var d = { - // "ct": 112, - // "v": 2.1, - // "debugFlag": true - // } - // callback({ - // status: true, - // data: { - // "cmdReceiveType" : "cmd", - // "connectionCnt" : connectionCnt, - // "data" : d - // }, - // message: "Debug flag" - // }) - // }, 150000); - - // setTimeout(() => { - // var d = { - // "ct": 113, - // "v": 2.1, - // "skipValidation": true - // } - // callback({ - // status: true, - // data: { - // "cmdReceiveType" : "cmd", - // "connectionCnt" : connectionCnt, - // "data" : d - // }, - // message: "Skip data validation" - // }) - // }, 300000); - - // setTimeout(() => { - // var d = { - // "ct": 114, - // "v": 2.1, - // "skipValidation": false - // } - // callback({ - // status: true, - // data: { - // "cmdReceiveType" : "cmd", - // "connectionCnt" : connectionCnt, - // "data" : d - // }, - // message: "Skip data validation" - // }) - // }, 50000); - - // setTimeout(() => { - // var d = { - // "ct": 115, - // "v": 2.1, - // "skipValidation": false - // } - // callback({ - // status: true, - // data: { - // "cmdReceiveType" : "cmd", - // "connectionCnt" : connectionCnt, - // "data" : d - // }, - // message: "Skip data validation" - // }) - // }, 50000); self.connectionError = false; var deviceCommandAck = { ct: config.commandType.DEVICE_CONNECTION_STATUS, uniqueId: self.UNIQUEID, sid: self.SID, - command: true - } + command: true, + }; callback({ status: true, data: { - "cmdReceiveType" : "cmd", - "connectionCnt" : connectionCnt, - "data" : deviceCommandAck + cmdReceiveType: "cmd", + connectionCnt: connectionCnt, + data: deviceCommandAck, }, - message: "Device connected" - }) + message: "Device connected", + }); connectionCnt++; - }) - + }); + self.mqttClient.on("message", function (topic, payload) { - // console.log("new command :::::::::::::::::::: ", JSON.stringify(JSON.parse(payload)) ); + console.log("\x1b[42m %s %s\x1b[0m", topic, JSON.stringify(JSON.parse(payload), null, 2)); if (topic.indexOf(twinPropertySubTopic.substring(0, twinPropertySubTopic.length - 1)) != -1) { - if(payload.toString('utf-8')) { + if (payload.toString("utf-8")) { var twinData = {}; - twinData['desired'] = JSON.parse(payload); + twinData["desired"] = JSON.parse(payload); twinData["uniqueId"] = self.UNIQUEID; callback({ status: true, data: { - "cmdReceiveType" : "twin", - "data" : twinData + cmdReceiveType: "twin", + data: twinData, }, - message: "Desired twin message received" - }) + message: "Desired twin message received", + }); } } else if (topic.indexOf(twinResponseSubTopic.substring(0, twinResponseSubTopic.length - 1)) != -1) { - if(payload.toString('utf-8')) { + if (payload.toString("utf-8")) { var twinData = JSON.parse(payload); twinData["uniqueId"] = self.UNIQUEID; callback({ status: true, data: { - "cmdReceiveType" : "twin", - "data" : twinData + cmdReceiveType: "twin", + data: twinData, }, - message: "All twin message received" - }) + message: "All twin message received", + }); } } else { callback({ status: true, data: { - "cmdReceiveType" : "cmd", - "connectionCnt" : connectionCnt, - "data" : JSON.parse(payload) + cmdReceiveType: "cmd", + connectionCnt: connectionCnt, + data: JSON.parse(payload), }, - message: "Device command" - }) + message: "Device command", + }); } - }) + }); - self.mqttClient.on('error', function (err) { - // console.log("Erro => ", err.message); + self.mqttClient.on("error", function (err) { self.connectionError = true; self.connectionErrorMessage = err.message; - }); - - self.mqttClient.on('close', function () { + }); + self.mqttClient.on("close", function (err) { var deviceCommandAck = { ct: config.commandType.DEVICE_CONNECTION_STATUS, uniqueId: self.UNIQUEID, sid: self.SID, - command: false - } - if(self.connectionError && self.connectionErrorMessage ) { - var msg = self.connectionErrorMessage + command: false, + }; + if (self.connectionError && self.connectionErrorMessage) { + var msg = self.connectionErrorMessage; } else { var msg = "Device disconnected"; } callback({ status: false, data: { - "cmdReceiveType" : "cmd", - "connectionCnt" : connectionCnt, - "data" : deviceCommandAck + cmdReceiveType: "cmd", + connectionCnt: connectionCnt, + data: deviceCommandAck, }, - message: msg - }) - - }) - + message: msg, + }); + }); } catch (error) { callback({ status: false, data: error, - message: error.message - }) + message: error.message, + }); } } - - /* - * Azure TPM SDK - * @author : MK - * Publish the message on cloud - * @param: sensorData, uniqueId, cpId - */ + + /* + * + * @author : MK + * Publish the message on cloud + * @param: sensorData, uniqueId, cpId + */ messagePublish(sensorData, callback) { try { - // console.log("Data 0 publish ==> ", JSON.stringify(sensorData)); var self = this; var pubTopic = sensorData.pubTopic; + var isTwin = false; // Temp comment to check for pub topic - if(sensorData.pubTopic) - delete sensorData.pubTopic; - - if(sensorData.mt || sensorData.mt == 0){ - if(!_.includes([200, 201, 202, 203, 204, 205, 210, 221, 222], sensorData.mt)) - delete sensorData.mt; + let message = ""; + if (sensorData.pubTopic) + if (sensorData.pubTopic.includes("twin") || sensorData.pubTopic.includes("shadow")) { + isTwin = true; + if (self.sdkOption.pf === "aws") { + message = "Shadow Updated Successfully"; + } else { + message = "Twin Updated Successfully"; + } + } + delete sensorData.pubTopic; + + if (sensorData.mt || sensorData.mt == 0) { + if (!_.includes([200, 201, 202, 203, 204, 205, 210, 221, 222], sensorData.mt)) delete sensorData.mt; - if("sid" in sensorData && sensorData.mt != config.msgType.all) - delete sensorData.sid; // Temp Data - } - if(!sensorData.sid && sensorData.cd){ + if ("sid" in sensorData && sensorData.mt != config.msgType.all) delete sensorData.sid; // Temp Data + } + if (!sensorData.sid && sensorData.cd) { delete sensorData.cd; } - - if(sensorData.twin == "all"){ + + if (sensorData.twin == "all") { sensorData = {}; } - - //console.log("Data 1 publish ==> ", JSON.stringify(sensorData)); self.mqttClient.publish(pubTopic, JSON.stringify(sensorData)); callback({ status: true, data: [], - message: "Message published successfully" - }) + message: isTwin == true ? message : "Message published successfully", + }); } catch (error) { callback({ status: false, data: error, - message: error.message - }) + message: error.message, + }); } } - /* - * Disconnect - * @author : MK - * Disconnect the device - * @param: - */ + /* + * Disconnect + * @author : MK + * Disconnect the device + * @param: + */ disconnect(callback) { var self = this; try { @@ -322,17 +236,16 @@ class MqttClient { callback({ status: true, data: [], - message: config.infoLog.INFO_IN03 - }) + message: config.infoLog.INFO_IN03, + }); } catch (error) { callback({ status: false, data: error, - message: error.message - }) + message: error.message, + }); } } - } -module.exports = MqttClient; \ No newline at end of file +module.exports = MqttClient; diff --git a/iotconnect-sdk/client/tpmClient.js b/iotconnect-sdk/client/tpmClient.js deleted file mode 100644 index 37217bd..0000000 --- a/iotconnect-sdk/client/tpmClient.js +++ /dev/null @@ -1,494 +0,0 @@ - -var config = require('../config/config'); -var ProvisioningTransport = require('azure-iot-provisioning-device-http').Http; -var Protocol = require('azure-iot-device-mqtt').Mqtt; -var Client = require('azure-iot-device').Client; -var Message = require('azure-iot-device').Message; -var tpmSecurity = require('azure-iot-security-tpm'); -var ProvisioningDeviceClient = require('azure-iot-provisioning-device').ProvisioningDeviceClient; -var provisioningServiceClient = require('azure-iot-provisioning-service').ProvisioningServiceClient; -var tssJs = require("tss.js"); - -class TpmClient { - - constructor(sId, uniqueId, sdkOption){ - this.SID = sId; - this.UNIQUEID = uniqueId; - // console.log("sdk Options tpm client => ", sdkOption); - this.CONNECTION_STRING = sdkOption.CONNECTION_STRING; - this.REGISTARTION_ID = sdkOption.TPM.TPM_DEVICE_REGISTRATION_ID; - this.IS_SIMULATED_TPM_DEVICE = sdkOption.TPM.IS_SIMULATED_TPM_DEVICE; - this.DPS_PROVISIONING_HOST_URL = sdkOption.TPM.DPS_PROVISIONING_HOST_URL; - this.DEVICE_REGISTRATION_ID = sdkOption.TPM.DEVICE_REGISTRATION_ID; - this.TPM_INITIAL_TWIN_SID = sdkOption.TPM.TPM_INITIAL_TWIN_SID; - this.SID_TPM_VERSION = sdkOption.TPM.SID_TPM_VERSION; - this.AZURE_IOT_EDGE_DEVICE = sdkOption.TPM.AZURE_IOT_EDGE_DEVICE; - this.SCOPE_ID = sdkOption.TPM.SCOPE_ID; - this.DPS_CONNECTION_STRING = sdkOption.TPM.DPS_CONNECTION_STRING; - this.ENDORCEMENT_KEY = sdkOption.TPM.ENDORCEMENT_KEY; - this.IOTHUB_HOST_NAME = sdkOption.TPM.IOTHUB_HOST_NAME; - this.IOT_HUB_HOST = ""; - if(this.IS_SIMULATED_TPM_DEVICE) { // For Simulator device - this.SECURITY_CLIENT = new tpmSecurity.TpmSecurityClient(this.REGISTARTION_ID, new tssJs.Tpm(true)); - } else { // For Production if using non-simulated device, replace the above line with following: - this.SECURITY_CLIENT = new tpmSecurity.TpmSecurityClient(); // Production - } - this.tpmClient = ""; - this.TWIN_PROPERTY = ""; - } - - /* - * Azure TPM SDK - * @author : MK - * Enroll the device into the DPS account - * @param: - */ - deviceEnrollment(callback){ - try { - var self = this; - // console.log("dpsConnectionsString => ", dpsConnectionsString); - // console.log("endorcementKey => ", endorcementKey); - // console.log("reg ID => ", self.REGISTARTION_ID); - var serviceClient = provisioningServiceClient.fromConnectionString(self.DPS_CONNECTION_STRING); - - serviceClient.getIndividualEnrollment(self.REGISTARTION_ID, function (err, deviceEnrollmentStatus) { - // console.log("deviceEnrollment Status => ", err.response.statusCode); - // console.log("deviceEnrollment Status => ", deviceEnrollmentStatus); - - if(err && err.response.statusCode == 404) { - - var enrollment = { - registrationId: self.REGISTARTION_ID, - initialTwin: { - tags: null, - properties: { - desired: {'sid': self.TPM_INITIAL_TWIN_SID,'idScope': self.SCOPE_ID,'version': self.SID_TPM_VERSION} - } - }, - capabilities: { - iotEdge: self.AZURE_IOT_EDGE_DEVICE - }, - attestation: { - type: 'tpm', - tpm: { - endorsementKey: self.ENDORCEMENT_KEY - } - } - }; - // console.log(" enrollment => ", enrollment); - serviceClient.createOrUpdateIndividualEnrollment(enrollment, function (err, enrollmentResponse) { - // console.log("get enrollmentResponse => ", enrollmentResponse); - if (err) { - callback({ - status: false, - data: null, - message: "Device enrollment failed : "+ err.message - }) - } else { - callback({ - status: true, - data: enrollmentResponse, - message: config.infoLog.INFO_IN16 - }) - } - }); - - } else { - // console.log("deviceEnrollmentStatus => else => ", deviceEnrollmentStatus); - - if(deviceEnrollmentStatus) { - callback({ - status: true, - data: deviceEnrollmentStatus, - message: config.infoLog.INFO_IN18 - }) - } - } - }); - } catch (error) { - callback({ - status: false, - data: null, - message: "Get Device enrollment detail failed : "+ error.message - }) - } - } - - /* - * Azure TPM SDK - * @author : MK - * Enroll the device from DPS to IoThub - * @param: - */ - deviceDPSProvisioning(callback){ - try { - // console.log("1.0.2") - var self = this; - var provisioningHost = config.dpsHostUrl; - var idScope = self.SCOPE_ID; - // console.log("provisioningHost => ", provisioningHost); - // console.log("idScope => ", idScope); - // console.log("client sdkOptions => ", self.REGISTARTION_ID); - // console.log("self.DEVICE_REGISTRATION_ID ==> ", self.DEVICE_REGISTRATION_ID) - var provisioningClient = ProvisioningDeviceClient.create(provisioningHost, idScope, new ProvisioningTransport(), self.SECURITY_CLIENT); - - if(!self.IS_SIMULATED_TPM_DEVICE) { - provisioningClient._securityClient._registrationId = self.DEVICE_REGISTRATION_ID; - } else { - provisioningClient._securityClient._registrationId = self.DEVICE_REGISTRATION_ID; - } - // console.log("1.0.3 => "); - provisioningClient.register(function(err, result) { - if (err) { - // console.error("error registering device: " + err.message); - callback({ - status: false, - data: null, - message: "Device provisioning failed : "+err.message - }) - } else { - self.IOT_HUB_HOST = result.registrationState.assignedHub; - // console.log('registration succeeded'); - callback({ - status: true, - data: null, - message: config.infoLog.INFO_IN17 - }) - } - }); - } catch (error) { - callback({ - status: false, - data: null, - message: "Device provisioning failed : "+error.message - }) - } - } - - /* - * Azure TPM SDK - * @author : MK - * Create client connection - * @param: - */ - clientConnection(callback) { - var self = this; - try { - var tpmAuthenticationProvider = tpmSecurity.TpmAuthenticationProvider.fromTpmSecurityClient(self.DEVICE_REGISTRATION_ID, self.IOT_HUB_HOST, self.SECURITY_CLIENT); - self.tpmClient = Client.fromAuthenticationProvider(tpmAuthenticationProvider, Protocol); - self.tpmClient._maxOperationTimeout = 30000; - - callback({ - status: true, - data: self.tpmClient, - message: "Device Connected success fully" - }) - } catch (error) { - // console.log("connection error => ", error); - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - * Azure TPM SDK - * @author : MK - * Subscribe the command and twin messages - * @param: uniqueId, cpId - */ - subscribeData(callback) { - try { - var self = this; - let twinCountCall = 0; - if (self.tpmClient) { - // console.log("self.tpmClient => ", self.tpmClient._maxOperationTimeout); - // self.tpmClient._maxOperationTimeout = 10000; - // console.log("self.tpmClient => ", self.tpmClient); - self.tpmClient.on('connect', function (err) { - console.log("Device connected => ", new Date()); - var deviceCommandAck = { - cmdType: config.commandType.DEVICE_CONNECTION_STATUS, - data: { - cpid: self.SID, - guid: '', - uniqueId: self.UNIQUEID, - command: true, - ack: false, - ackId: '', - cmdType: config.commandType.DEVICE_CONNECTION_STATUS - } - } - callback({ - status: true, - data: { - "cmdReceiveType" : "cmd", - "data" : deviceCommandAck - }, - message: "Device connected" - }) - // callback(deviceCommandAck); - }); - self.tpmClient.on('disconnect', function () { - // self.tpmClient.removeAllListeners(); - console.log("Device disconnected => ", new Date()); - var deviceCommandAck = { - cmdType: config.commandType.DEVICE_CONNECTION_STATUS, - data: { - cpid: self.SID, - guid: '', - uniqueId: self.UNIQUEID, - command: false, - ack: false, - ackId: '', - cmdType: config.commandType.DEVICE_CONNECTION_STATUS - } - } - callback({ - status: true, - data: { - "cmdReceiveType" : "cmd", - "data" : deviceCommandAck - }, - message: "Device disconnected" - }) - }); - self.tpmClient.open(function (err) { - if (err) { - callback({ - status: false, - data: null, - message: err.message - }) - } else { - - self.tpmClient.on('message', function (msg) { - console.log('Id: ' + msg.messageId + ' Body: ' , JSON.parse(msg.data)); - // callback(JSON.parse(msg.data)); - callback({ - status: true, - data: { - "cmdReceiveType" : "cmd", - "data" : JSON.parse(msg.data) - }, - message: "Device command" - }) - }); - // self.tpmClient.on('error', function (err) { - // console.error(err.message); - // }); - self.tpmClient.getTwin(function (err, twin) { - self.twinProperty = twin; - if (err) { - callback({ - status: false, - data: err, - message: err.message - }) - } else { - twin.on('properties.desired', function(delta) { - var twinData = {}; - twinData['desired'] = delta; - twinData["uniqueId"] = self.UNIQUEID; - if(twinCountCall == 0){ - twinCountCall++; - } else { - callback({ - status: true, - data: { - "cmdReceiveType" : "twin", - "data" : twinData - }, - message: "All twin message received" - }) - // GLOBAL_CALLBACK_TWIN(twinData); - } - }); - } - }); - } - }); - } else { - callback({ - status: false, - data: error, - message: config.errorLog.ERR_IN11 - }) - } - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - * Azure TPM SDK - * @author : MK - * Publish the message on cloud - * @param: sensorData, uniqueId, cpId - */ - messagePublish(sensorData, callback) { - try { - var self = this; - if(sensorData){ - if(sensorData.mt || sensorData.mt == 0){ - var message = new Message(JSON.stringify(sensorData)); - } else { - if("sid" in sensorData) - delete sensorData.sid; // Temp Data - var message = new Message(JSON.stringify(sensorData)); - } - } - console.log('Sending message: ', message); - try { - self.tpmClient.sendEvent(message, self.printResultFor('send', self.SID + "_" + self.UNIQUEID)); - // self.tpmClient.sendEvent(message, self.printResultFor('send', cpId + "_" + uniqueId)); - - } catch (error) { - console.log("error -> ", error ); - } - callback({ - status: true, - data: [], - message: "Message published successfully" - }) - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - // Helper function to print results in the console - printResultFor(op, id = "") { - return function printResult(err, res) { - if (err) { - // console.log("\nPublishData ::: " + id + " :: status :: ERROR - " + err.toString() + " :: ", new Date()); - } - if (res) { - if (op == 'send') { - // console.log("\nPublishData ::: " + id + " :: status :: " + res.constructor.name + " :: ", new Date()); - } else if (op == 'completed') { - // console.log("\nReceivedData ::: " + id + " :: status :: " + res.constructor.name + " :: ", new Date()); - } - } - }; - } - - /* - * Azure TPM SDK - * @author : MK - * Get Twin desired property - * @param: uniqueId, cpId - */ - getTwinProperty(callback) { - try { - var self = this; - self.tpmClient.getTwin(function (err, twin) { - if (err) { - callback({ - status: false, - data: err, - message: err.message - }) - } else { - callback({ - status: true, - data: null, - message: "Twin message request sent" - }) - } - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - * Azure TPM SDK - * @author : MK - * Update Twin reported property - * @param: data {key: value} - */ - updateTwinProperty(patch, callback) { - try { - var self = this; - var twin = self.twinProperty; - twin.properties.reported.update(patch, function(err) { - if (err) - { - callback({ - status: false, - data: err, - message: err.message - }) - } else { - callback({ - status: true, - data: [], - message: "Twin updated successfully" - }) - } - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - * Azure TPM SDK - * @author : MK - * Disconnect the device - * @param: - */ - disconnect(callback) { - var self = this; - try { - console.log("In client => "); - self.tpmClient.close(function (err){ - console.log("In client => ", err); - if(err) { - callback({ - status: false, - data: [], - message: err.message - }) - } else { - callback({ - status: true, - data: [], - message: "Client disconnected successfully" - }) - } - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - -} - -module.exports = TpmClient; \ No newline at end of file diff --git a/iotconnect-sdk/common/common.js b/iotconnect-sdk/common/common.js index eb9720a..1b1690b 100644 --- a/iotconnect-sdk/common/common.js +++ b/iotconnect-sdk/common/common.js @@ -9,10 +9,15 @@ var mqtt = require('mqtt'); var fs = require('fs-extra'); var fsep = require('fs-extra-promise'); var config = require('./../config/config'); +var moment = require('moment'); +const isOnline = require('is-online'); + const { authType } = require('./../config/config'); +let lastEdgeFaultyDataTime = new Date().getTime(); + class CommonFunctions { constructor(sId, uniqueId, sdkOption) { @@ -33,10 +38,6 @@ class CommonFunctions { if (sdkOption.SDK_TYPE == "MQTT") { deviceClient = require("./../client/mqttClient"); - } else if (sdkOption.SDK_TYPE == "AZURE") { - deviceClient = require("./../client/azClient"); - } else if (sdkOption.SDK_TYPE == "TPM") { - deviceClient = require("./../client/tpmClient"); } this.BROKER_CLIENT = new deviceClient(sId, uniqueId, sdkOption); this.INTERVAL_OBJ = []; @@ -51,12 +52,19 @@ class CommonFunctions { */ getBaseUrl(callback) { var self = this; - var url = self.SDK_OPTIONS.discoveryUrl + config.discoveryBaseUrl; + var url = self.SDK_OPTIONS.discoveryUrl; var discoveryUrl = ""; async.series([ function (cb_series) { - discoveryUrl = url.replace("<>", self.SID); + + if(self.SDK_OPTIONS.cpId){ + discoveryUrl = url + config.discoveryUrlwithCpid; + discoveryUrl = discoveryUrl.replace("<>", self.SDK_OPTIONS.cpId).replace("<>", self.SDK_OPTIONS.env).replace("<>", self.SDK_OPTIONS.pf); + } else { + discoveryUrl = url + config.discoveryBaseUrl; + discoveryUrl = discoveryUrl.replace("<>", self.SID); + } cb_series(); } ], function (err, response) { @@ -122,7 +130,7 @@ class CommonFunctions { self.getBaseUrl(function (status, responseData) { if (status == true && responseData.d.bu) { let syncBaseUrl = responseData.d.bu + "/uid/" + self.UNIQUEID; - console.log("CommonFunctions -> syncDevice -> syncBaseUrl", syncBaseUrl) + self.manageDebugLog("INFO_IN07", self.UNIQUEID, self.SID, syncBaseUrl, 1, true); request.get({ url: syncBaseUrl, json: true @@ -146,7 +154,7 @@ class CommonFunctions { } } else { if (response && response.statusCode == 200 && body != undefined && body.d.ec == 0) { - console.log("CommonFunctions -> syncDevice -> body.d", body.d) + self.manageDebugLog("INFO_IN07", self.UNIQUEID, self.SID, JSON.stringify(body.d,null,2), 1, true); if (body.d.meta.v == config.msgFormatVersion) { self.manageDebugLog("INFO_IN01", self.UNIQUEID, self.SID, "", 1, self.IS_DEBUG); var resultData = body.d; @@ -805,7 +813,7 @@ class CommonFunctions { if (deviceData.meta.edge == config.edgeEnableStatus.enabled) { attributeObj.d = _.reduce(attributeObj.d, _.extend); dataObj.d.push(attributeObj); - self.sendDataOnAzureMQTT(dataObj); + self.sendDataOnMQTT(dataObj); } }) } @@ -926,17 +934,17 @@ class CommonFunctions { data: deviceData }) if (self.SDK_OPTIONS.isGatewayDevice) { - tag = resultDevice.value[0].tg; + tag = resultDevice.value[0]?.tg; } else { tag = undefined; } - attributeObj["id"] = self.SDK_OPTIONS.isGatewayDevice ? uniqueId : undefined; + attributeObj["id"] =uniqueId// self.SDK_OPTIONS.isGatewayDevice ? uniqueId : undefined; attributeObj["dt"] = deviceSendTime; attributeObj["tg"] = tag ? tag : undefined; attributeObj["d"] = []; - attributeObjFLT["id"] = self.SDK_OPTIONS.isGatewayDevice ? uniqueId : undefined; + attributeObjFLT["id"] = uniqueId//self.SDK_OPTIONS.isGatewayDevice ? uniqueId : undefined; attributeObjFLT["dt"] = deviceSendTime; attributeObjFLT["tg"] = tag ? tag : undefined; attributeObjFLT["d"] = []; @@ -948,12 +956,13 @@ class CommonFunctions { var withoutParentRuleAttrObj = {}; var parentRuleAttrObj = {}; var ruleAttributeValidateArray = []; + var parentDeviceAttributeInfo = []; + var ruleValueFlag = 0; async.forEachSeries(Object.keys(data), function (attributeKey, cb_fl_dData) { var parentAttrObj = {} var parentAttrObjFLT = {} - if (typeof data[attributeKey] == "object") // true = Parent attribute - { + if (typeof data[attributeKey] == "object") {// true = Parent attribute, Attribute is of Object Type var parentChildArray = data[attributeKey]; if (self.SDK_OPTIONS.isGatewayDevice && tag) { var resultDevice = jsonQuery('att[*p=' + attributeKey + ' & tg=' + tag + ']', { @@ -964,72 +973,96 @@ class CommonFunctions { data: deviceData }) } - if (resultDevice.value.length > 0) { - async.forEachSeries(resultDevice.value, function (parentdeviceInfo, cb_fl_pdi) { + if (resultDevice.value?.length > 0) { + async.forEachSeries(Object.keys(parentChildArray), function (parentChildKey, cb_fl_child) {// START - Traverse all child Attribute in Object + async.forEachSeries(resultDevice.value, function (parentdeviceInfo, cb_fl_pdi) {// START - Traverse all keys in Object for Current Attribute's Value + // parentdeviceInfo = deviceInfo from server + // console.log("AWS NODE ~ file: common.js:978 ~ parentdeviceInfo:", parentdeviceInfo) var parentAttributeName = parentdeviceInfo.p; - var parentDeviceAttributeInfo = []; - var ruleValueFlag = 0; - async.forEachSeries(parentdeviceInfo.d, function (childDeviceInfo, cb_fl_cdi) { - async.forEachSeries(Object.keys(parentChildArray), function (parentChildKey, cb_fl_child) { - var msgTypeStatus = 0; - var attrValue = 0; - if (parentChildKey == childDeviceInfo.ln) { - var dataType = childDeviceInfo.dt; - var dataValidation = childDeviceInfo.dv; - attrValue = parentChildArray[parentChildKey]; - if (attrValue != "") { - self.dataValidationTest(dataType, dataValidation, attrValue, childDeviceInfo, msgTypeStatus, function (childAttrObj) { - if (childAttrObj.msgTypeStatus == 1) //msgTypeStatus = 1 (Validation Failed) - { - if (!parentAttrObjFLT[parentAttributeName]) - parentAttrObjFLT[parentAttributeName] = {}; - delete childAttrObj['msgTypeStatus']; - parentAttrObjFLT[parentAttributeName][childAttrObj.ln] = childAttrObj.v; - cntFLT++; - } else { - if (deviceData.meta.edge == config.edgeEnableStatus.enabled && (dataType == config.dataType.INTEGER || dataType == config.dataType.LONG || dataType == config.dataType.DECIMAL)) // Its Edge Enable Device + var parentDevicechildDeviceInfoAttributeInfo = []; + ruleValueFlag = 0; + if(_.find(parentdeviceInfo.d, { "ln" : parentChildKey})){ + + + + async.forEachSeries(parentdeviceInfo.d, function (childDeviceInfo, cb_fl_cdi) { + var msgTypeStatus = 0; + var attrValue = 0; + if (parentChildKey == childDeviceInfo.ln) { + var dataType = childDeviceInfo.dt; + var dataValidation = childDeviceInfo.dv; + attrValue = parentChildArray[parentChildKey]; + if (attrValue !== "") { + self.dataValidationTest(dataType, dataValidation, attrValue, childDeviceInfo, msgTypeStatus, function (childAttrObj) { + if (childAttrObj.msgTypeStatus == 1) //msgTypeStatus = 1 (Validation Failed) { - ruleValueFlag = 1; - childDeviceInfo.parentGuid = parentdeviceInfo.guid; - childDeviceInfo.p = parentAttributeName; - childDeviceInfo.value = attrValue; - parentDeviceAttributeInfo.push(childDeviceInfo); - self.setEdgeVal(childDeviceInfo, attrValue, uniqueId); - if (!parentRuleAttrObj[parentAttributeName]) - parentRuleAttrObj[parentAttributeName] = {}; - parentRuleAttrObj[parentAttributeName][childAttrObj.ln] = childAttrObj.v; - } else { - if (!parentAttrObj[parentAttributeName]) - parentAttrObj[parentAttributeName] = {}; + if (!parentAttrObjFLT[parentAttributeName]) + parentAttrObjFLT[parentAttributeName] = {}; delete childAttrObj['msgTypeStatus']; - parentAttrObj[parentAttributeName][childAttrObj.ln] = childAttrObj.v; - cntRPT++; + parentAttrObjFLT[parentAttributeName][childAttrObj.ln] = childAttrObj.v; + cntFLT++; + } else { + if (deviceData.meta.edge == config.edgeEnableStatus.enabled && (dataType == config.dataType.INTEGER || dataType == config.dataType.LONG || dataType == config.dataType.DECIMAL)) // Its Edge Enable Device + { + ruleValueFlag = 1; + childDeviceInfo.parentGuid = parentdeviceInfo.guid; + childDeviceInfo.p = parentAttributeName; + childDeviceInfo.value = attrValue; + parentDeviceAttributeInfo.push(childDeviceInfo); + self.setEdgeVal(childDeviceInfo, attrValue, uniqueId); + if (!parentRuleAttrObj[parentAttributeName]) + parentRuleAttrObj[parentAttributeName] = {}; + parentRuleAttrObj[parentAttributeName][childAttrObj.ln] = childAttrObj.v; + } else { + if (!parentAttrObj[parentAttributeName]) + parentAttrObj[parentAttributeName] = {}; + delete childAttrObj['msgTypeStatus']; + parentAttrObj[parentAttributeName][childAttrObj.ln] = childAttrObj.v; + cntRPT++; + } } - } - cb_fl_child(); - }) + cb_fl_cdi(); + }) + } else { + cb_fl_cdi(); + } } else { - cb_fl_child(); + cb_fl_cdi(); } - } else { - cb_fl_child(); + }, function () { + // cb_fl_child(); + cb_fl_pdi(); + }); + } else { + if (!parentAttrObjFLT[parentAttributeName]) + parentAttrObjFLT[parentAttributeName] = {}; + parentAttrObjFLT[parentAttributeName][parentChildKey] = parentChildArray[parentChildKey]; + cntFLT++; + cb_fl_pdi(); + } + }, function () { // END - Traverse all keys in Object for Current Attribute's Value + if (deviceData.meta.edge == config.edgeEnableStatus.enabled && ruleValueFlag == 1) // Its Edge Enable Device + { + var tobj = { + "parentDeviceAttributeInfo": parentDeviceAttributeInfo, + "attrValue": null, + "attributeObj": attributeObj + } + ruleAttributeValidateArray.push(tobj); } - }, function () { - cb_fl_cdi(); + cb_fl_child(); }); - }, function () { - if (deviceData.meta.edge == config.edgeEnableStatus.enabled && ruleValueFlag == 1) // Its Edge Enable Device - { - var tobj = { - "parentDeviceAttributeInfo": parentDeviceAttributeInfo, - "attrValue": null, - "attributeObj": attributeObj - } - ruleAttributeValidateArray.push(tobj); - } - cb_fl_pdi(); - }); - }, function () { + // } else { + // // delete childAttrObj['msgTypeStatus']; + // // if (!parentAttrObjFLT[parentAttributeName]) + // // parentAttrObjFLT[parentAttributeName] = {}; + // // delete childAttrObj['msgTypeStatus']; + // // parentAttrObjFLT[parentAttributeName][childAttrObj.ln] = childAttrObj.v; + // parentAttrObjFLT[attributeKey] = data[attributeKey]; + // cntFLT++; + // cb_fl_dData(); + // } + }, function () { // END - Traverse all child Attribute in Object if (parentAttrObjFLT) { attributeObjFLT.d.push(parentAttrObjFLT); } @@ -1039,62 +1072,76 @@ class CommonFunctions { cb_fl_dData(); }); } else { + if (!parentAttrObjFLT[attributeKey]) + parentAttrObjFLT[attributeKey] = {}; + parentAttrObjFLT[attributeKey] = parentChildArray; + cntFLT++; + if (parentAttrObjFLT) { + attributeObjFLT.d.push(parentAttrObjFLT); + } cb_fl_dData(); } } else { // No Parent async.forEachSeries(deviceData.att, function (noParentDeviceInfo, cb_fl_npdi) { if (noParentDeviceInfo.p == "") { var parentAttributeName = noParentDeviceInfo.p; - async.forEachSeries(noParentDeviceInfo.d, function (childDeviceInfo, cb_fl_cdi) { - var msgTypeStatus = 0; - var tgflag = false; - if (self.SDK_OPTIONS.isGatewayDevice && tag && childDeviceInfo.tg == tag) { - tgflag = true; - } - if (!self.SDK_OPTIONS.isGatewayDevice && !tag) { - tgflag = true; - } - if (tgflag && attributeKey == childDeviceInfo.ln) { - var attrValue = data[attributeKey]; - var dataType = childDeviceInfo.dt; - var dataValidation = childDeviceInfo.dv; - if (attrValue != "") { - self.dataValidationTest(dataType, dataValidation, attrValue, childDeviceInfo, msgTypeStatus, function (childAttrObj) { - if (childAttrObj.msgTypeStatus == 1) //msgTypeStatus = 1 (Validation Failed) - { - delete childAttrObj['msgTypeStatus']; - withoutParentAttrObjFLT[childAttrObj.ln] = childAttrObj.v; - cntFLT++; - } else { - if (deviceData.meta.edge == config.edgeEnableStatus.enabled && (dataType == config.dataType.INTEGER || dataType == config.dataType.LONG || dataType == config.dataType.DECIMAL)) // Its Edge Enable Device + if(_.find(noParentDeviceInfo.d, { "ln" : attributeKey})){ + async.forEachSeries(noParentDeviceInfo.d, function (childDeviceInfo, cb_fl_cdi) { + var msgTypeStatus = 0; + var tgflag = false; + if (self.SDK_OPTIONS.isGatewayDevice && tag && childDeviceInfo.tg == tag) { + tgflag = true; + } + if (!self.SDK_OPTIONS.isGatewayDevice && !tag) { + tgflag = true; + } + if (tgflag && attributeKey == childDeviceInfo.ln) { + var attrValue = data[attributeKey]; + var dataType = childDeviceInfo.dt; + var dataValidation = childDeviceInfo.dv; + if (attrValue !== "" ) { + self.dataValidationTest(dataType, dataValidation, attrValue, childDeviceInfo, msgTypeStatus, function (childAttrObj) { + if (childAttrObj.msgTypeStatus == 1) //msgTypeStatus = 1 (Validation Failed) { - childDeviceInfo.parentGuid = noParentDeviceInfo.guid; - childDeviceInfo.p = parentAttributeName; - self.setEdgeVal(childDeviceInfo, attrValue, uniqueId); - var tobj = { - "parentDeviceAttributeInfo": childDeviceInfo, - "attrValue": attrValue, - "attributeObj": attributeObj - } - ruleAttributeValidateArray.push(tobj); - withoutParentRuleAttrObj[childAttrObj.ln] = childAttrObj.v; - } else { delete childAttrObj['msgTypeStatus']; - withoutParentAttrObj[childAttrObj.ln] = childAttrObj.v; - cntRPT++; + withoutParentAttrObjFLT[childAttrObj.ln] = childAttrObj.v; + cntFLT++; + } else { + if (deviceData.meta.edge == config.edgeEnableStatus.enabled && (dataType == config.dataType.INTEGER || dataType == config.dataType.LONG || dataType == config.dataType.DECIMAL)) // Its Edge Enable Device + { + childDeviceInfo.parentGuid = noParentDeviceInfo.guid; + childDeviceInfo.p = parentAttributeName; + self.setEdgeVal(childDeviceInfo, attrValue, uniqueId); + var tobj = { + "parentDeviceAttributeInfo": childDeviceInfo, + "attrValue": attrValue, + "attributeObj": attributeObj + } + ruleAttributeValidateArray.push(tobj); + withoutParentRuleAttrObj[childAttrObj.ln] = childAttrObj.v; + } else { + delete childAttrObj['msgTypeStatus']; + withoutParentAttrObj[childAttrObj.ln] = childAttrObj.v; + cntRPT++; + } } - } + cb_fl_cdi(); + }) + } else { cb_fl_cdi(); - }) + } } else { cb_fl_cdi(); } - } else { - cb_fl_cdi(); - } - }, function () { + }, function () { + cb_fl_npdi(); + }); + } else { + // delete childAttrObj['msgTypeStatus']; + withoutParentAttrObjFLT[attributeKey] = data[attributeKey]; + cntFLT++; cb_fl_npdi(); - }); + } } else { cb_fl_npdi(); } @@ -1123,7 +1170,8 @@ class CommonFunctions { }); } ], function (err, response) { - if (cntFLT > 0 && deviceData.meta.edge == config.edgeEnableStatus.disabled) { + // Edge Faulty TODO + if (cntFLT > 0 ) { attributeObjFLT.d = _.reduce(attributeObjFLT.d, _.extend); dataObjFLT.d.push(attributeObjFLT) } @@ -1140,13 +1188,21 @@ class CommonFunctions { cb_f2_dData(); } }, function () { + // Edge Faulty TODO + if(parseInt(new Date().getTime()) >= lastEdgeFaultyDataTime + config.edgeFaultDataFrequency){ + if (dataObjFLT.d.length > 0 && deviceData.meta.edge == config.edgeEnableStatus.enabled) { + // console.log("===> flt => ", JSON.stringify(dataObjFLT)); + lastEdgeFaultyDataTime = new Date().getTime() + self.sendDataOnMQTT(dataObjFLT); + } + } if (dataObjFLT.d.length > 0 && deviceData.meta.edge == config.edgeEnableStatus.disabled) { // console.log("===> flt => ", JSON.stringify(dataObjFLT)); - self.sendDataOnAzureMQTT(dataObjFLT); + self.sendDataOnMQTT(dataObjFLT); } if (dataObj.d.length > 0 && deviceData.meta.edge == config.edgeEnableStatus.disabled) { // console.log("===> rpt => ", JSON.stringify(dataObj)); - self.sendDataOnAzureMQTT(dataObj); + self.sendDataOnMQTT(dataObj); } }); } catch (error) { @@ -1175,7 +1231,7 @@ class CommonFunctions { var eekey = actualDeviceId + "-" + attributeInfo.p; } var edgeObj = edgeDatObj[eekey]; - async.forEachSeries(edgeObj.data, function (atrributeData, cb) { + async.forEachSeries(edgeObj?.data, function (atrributeData, cb) { atrributeData["agt"] = config.aggregateType; if (attributeInfo.ln == atrributeData.localName) { var newAtrrValue = atrributeData; @@ -1226,7 +1282,7 @@ class CommonFunctions { } var edgeObj = edgeDatObj[eekey]; - async.forEachSeries(edgeObj.data, function (atrributeData, cb) { + async.forEachSeries(edgeObj?.data, function (atrributeData, cb) { atrributeData["agt"] = attributeInfo.agt; var newAtrrValue = atrributeData; var inputCounter = parseInt(atrributeData.count) + 1; @@ -1602,7 +1658,7 @@ class CommonFunctions { } self.sendCommand(cmdObj); newObj.d.push(attributeObj); - self.sendDataOnAzureMQTT(newObj); + self.sendDataOnMQTT(newObj); } else { // Not Matched rule self.manageDebugLog("INFO_EE02", self.UNIQUEID, self.SID, "", 1, self.IS_DEBUG); } @@ -1685,7 +1741,7 @@ class CommonFunctions { cb_rl(); }, function () { if (ruleFlag == 1) { - self.sendDataOnAzureMQTT(newObj); + self.sendDataOnMQTT(newObj); } }); } @@ -1724,8 +1780,8 @@ class CommonFunctions { //console.log('datatype', dataType) var self = this; var childAttrObj = {}; + var valueArray = dataValidation.split(","); if (dataType == config.dataType.INTEGER || dataType == config.dataType.LONG) { - var valueArray = dataValidation.split(","); var attrValue = attrValue.toString(); var numbersInt = /^[-+]?[0-9]+$/; var numbersFloat = /^[-+]?[0-9]+\.[0-9]+$/; @@ -1804,7 +1860,343 @@ class CommonFunctions { childAttrObj["v"] = attrValue; } childAttrObj["msgTypeStatus"] = msgTypeStatus; - }else { + }else if (dataType == config.dataType.BIT) { + var attrValue1 = attrValue.toString(); + if(!attrValue1.match(/^(0|1)$/)) { + msgTypeStatus = 1; + } + + if(self.SDK_OPTIONS.isSkipValidation) { + if (isNumber == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } else { + if (dataValidation != "" && dataValidation != null) { + if (valueArray.indexOf(attrValue) == -1) { + + var validationFlag = 1; + async.forEachSeries(valueArray, function (restrictedValue, cbValue) { + if (restrictedValue.indexOf("to") == -1) { + if (attrValue == parseInt(restrictedValue.trim())) { + validationFlag = 0; + } + cbValue(); + } else { + var valueRangeArray = restrictedValue.split("to"); + if (attrValue >= parseInt(valueRangeArray[0].trim()) && attrValue <= parseInt(valueRangeArray[1].trim())) { + validationFlag = 0; + } + cbValue(); + } + + }, function () { + if (validationFlag == 1 || isNumber == false) { + msgTypeStatus = 1; + } + + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + }); + } else { + if (isNumber == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } else { + if (isNumber == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } + }else if (dataType == config.dataType.BOOLEAN) { + var attrValue1 = attrValue.toString(); + if(!attrValue1.match(/^(true|false|False|True)$/)) { + msgTypeStatus = 1; + } + if(self.SDK_OPTIONS.isSkipValidation) { + if (isNumber == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } else { + if (dataValidation != "" && dataValidation != null) { + if (valueArray.indexOf(attrValue) == -1) { + + var validationFlag = 1; + async.forEachSeries(valueArray, function (restrictedValue, cbValue) { + if (restrictedValue.indexOf("to") == -1) { + if (attrValue == parseInt(restrictedValue.trim())) { + validationFlag = 0; + } + cbValue(); + } else { + var valueRangeArray = restrictedValue.split("to"); + if (attrValue >= parseInt(valueRangeArray[0].trim()) && attrValue <= parseInt(valueRangeArray[1].trim())) { + validationFlag = 0; + } + cbValue(); + } + + }, function () { + if (validationFlag == 1 || isNumber == false) { + msgTypeStatus = 1; + } + + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + }); + } else { + if (isNumber == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } else { + if (isNumber == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } + }else if (dataType == config.dataType.DECIMAL) { + var attrValue = attrValue.toString(); + var valueArray = dataValidation.split(","); + var isDecimal = false + if(!attrValue.match('^-?\\d+(\\.\\d{1,7})?$')) { + msgTypeStatus = 1; + isDecimal = false + } else if(attrValue.match('^-?\\d+(\\.\\d{1,7})?$')){ + if(!(Number(_.trim(attrValue)) >= Number((-7.9*1028).toString()) && Number(_.trim(attrValue)) <= Number((7.9*1028).toString()))){ + msgTypeStatus = 1 + isDecimal = false + } + else { + isDecimal = true + } + } else { + isDecimal = true + } + if(self.SDK_OPTIONS.isSkipValidation) { + if (isDecimal == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } else { + if (dataValidation != "" && dataValidation != null) { + if (valueArray.indexOf(attrValue) == -1) { + + var validationFlag = 1; + async.forEachSeries(valueArray, function (restrictedValue, cbValue) { + if (restrictedValue.indexOf("to") == -1) { + if (attrValue == Number(_.trim(restrictedValue))) { + validationFlag = 0; + } + cbValue(); + } else { + var valueRangeArray = restrictedValue.split("to"); + if (attrValue >= Number(_.trim(valueRangeArray[0])) && attrValue <= Number(_.trim(valueRangeArray[1]))) { + validationFlag = 0; + } + cbValue(); + } + + }, function () { + if (validationFlag == 1 || isDecimal == false) { + msgTypeStatus = 1; + } + + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + }); + } else { + if (isDecimal == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } else { + if (isDecimal == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + }else if (dataType == config.dataType.DATE) { + var attrValue1 = attrValue.toString(); + var valid = true + if(!moment(attrValue1, 'YYYY-MM-DD', true).isValid()) { + msgTypeStatus = 1; + valid = false + } + if(self.SDK_OPTIONS.isSkipValidation) { + if (valid == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } else { + if (dataValidation != "" && dataValidation != null) { + let isValidFlag = false + _.map(_.split(dataValidation, ','), function (group) { + let value = moment(attrValue1,'YYYY-MM-DD'); + if (group.includes('to')) { + let tmpArr = _.split(group, 'to'); + let beforeValue = moment(tmpArr[0].trim(),'YYYY-MM-DD'); + let afterValue = moment(tmpArr[1].trim(),'YYYY-MM-DD'); + if (value.isBetween(beforeValue, afterValue, undefined, '[]')) { + isValidFlag = true + } + if (value.isBefore(beforeValue)) { + isValidFlag = false + } if (value.isAfter(afterValue)) { + isValidFlag = false + } + } else { + let value2 = moment(group.trim(),'YYYY-MM-DD'); + if (value.isSame(value2)) { + isValidFlag = true + } + } + }); + if (!isValidFlag){ + msgTypeStatus = 1 + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + }else if (dataType == config.dataType.DATETIME) { + var attrValue1 = attrValue.toString(); + var valid = true + if(!moment(attrValue1, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]', true).isValid()) { + msgTypeStatus = 1; + valid = false + } + if(self.SDK_OPTIONS.isSkipValidation) { + if (valid == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } else { + if (dataValidation != "" && dataValidation != null) { + let isValidFlag = false + _.map(_.split(dataValidation, ','), function (group) { + let value = moment(attrValue1,'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + if (group.includes('to')) { + let tmpArr = _.split(group, 'to'); + let beforeValue = moment(tmpArr[0].trim(),'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + let afterValue = moment(tmpArr[1].trim(),'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + if (value.isBetween(beforeValue, afterValue, undefined, '[]')) { + isValidFlag = true + } + if (value.isBefore(beforeValue)) { + isValidFlag = false + } if (value.isAfter(afterValue)) { + isValidFlag = false + } + } else { + let value2 = moment(group.trim(),'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + if (value.isSame(value2)) { + isValidFlag = true + } + } + }); + if (!isValidFlag){ + msgTypeStatus = 1 + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + }else if (dataType == config.dataType.TIME) { + var attrValue1 = attrValue.toString(); + var valid = true + if(!moment(attrValue1, 'HH:mm:ss', true).isValid()) { + msgTypeStatus = 1; + valid = false + } + if(self.SDK_OPTIONS.isSkipValidation) { + if (valid == false) { + msgTypeStatus = 1; + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } else { + if (dataValidation != "" && dataValidation != null) { + let isValidFlag = false + _.map(_.split(dataValidation, ','), function (group) { + let value = moment(attrValue1,'HH:mm:ss'); + if (group.includes('to')) { + let tmpArr = _.split(group, 'to'); + let beforeValue = moment(tmpArr[0].trim(),'HH:mm:ss'); + let afterValue = moment(tmpArr[1].trim(),'HH:mm:ss'); + if (value.isBetween(beforeValue, afterValue, undefined, '[]')) { + isValidFlag = true + } + if (value.isBefore(beforeValue)) { + isValidFlag = false + } if (value.isAfter(afterValue)) { + isValidFlag = false + } + } else { + let value2 = moment(group.trim(),'HH:mm:ss'); + if (value.isSame(value2)) { + isValidFlag = true + } + } + }); + if (!isValidFlag){ + msgTypeStatus = 1 + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + } + childAttrObj["ln"] = childDeviceInfo.ln; + childAttrObj["v"] = attrValue; + childAttrObj["msgTypeStatus"] = msgTypeStatus; + } + else { childAttrObj["ln"] = childDeviceInfo.ln; childAttrObj["v"] = attrValue; childAttrObj["msgTypeStatus"] = msgTypeStatus; @@ -1818,7 +2210,7 @@ class CommonFunctions { Output : Send data using MQTT to MQTT topic Date : 2018-01-25 */ - sendDataOnAzureMQTT(sensorData) { + sendDataOnMQTT(sensorData) { var self = this; var cacheId = self.SID + "_" + self.UNIQUEID; var deviceSyncRes = cache.get(cacheId); @@ -1827,7 +2219,7 @@ class CommonFunctions { var protocoalName = brokerConfiguration.n; if (protocoalName.toLowerCase() == "mqtt" && deviceSyncRes && "p" in deviceSyncRes) { var mqttHost = brokerConfiguration.h; - //console.log("sendDataOnAzureMQTT -> mqttPublishData -> sensorData.mt", sensorData.d) + //console.log("sendDataOnMQTT -> mqttPublishData -> sensorData.mt", sensorData.d) self.mqttPublishData(mqttHost, sensorData); } else if (protocoalName.toLowerCase() == "http" || protocoalName.toLowerCase() == "https") { var headers = { @@ -1857,8 +2249,6 @@ class CommonFunctions { var mqttHost = self.SDK_OPTIONS.CONNECTION_STRING.split(";")[0].split("=")[1]; //console.log("Azure -> mqttPublishData -> sensorData", sensorData) self.mqttPublishData(mqttHost, sensorData); - } else if (self.SDK_OPTIONS.SDK_TYPE == "TPM") { - console.log("TPM Data send..."); } } @@ -1872,14 +2262,16 @@ class CommonFunctions { var self = this; try { - if (!offlineData['sid']) - offlineData['sid'] = self.SID; + // if (!offlineData['sid']) + offlineData['sid'] = self.SID; if (self.IS_RUNNING) { setTimeout(() => { + offlineData['sid'] = self.SID; self.offlineProcess(offlineData); }, 500); } else { self.IS_RUNNING = true; + offlineData['sid'] = self.SID; var logPath = self.LOG_PATH; try { fs.readdir(logPath, function (err, files) { @@ -1903,7 +2295,7 @@ class CommonFunctions { ], function (err, fileSize) { if (!offlineData.mt || offlineData.mt == config.messageType.ack) { if (offlineData.mt != 0) - delete offlineData.sid; // Temp code + // delete offlineData.sid; // Temp code var uid = self.UNIQUEID; } else { var uid = offlineData.d[0].id; @@ -1918,7 +2310,7 @@ class CommonFunctions { self.manageDebugLog("ERR_OS01", self.UNIQUEID, self.SID, err.message, 0, self.IS_DEBUG); cb(); } else { - // console.log("\nOffline data saved ::: DeviceId :: " + clientId + " :: ", new Date()); + console.log("\nOffline data saved ::: DeviceId :: " + self.UNIQUEID + " :: ", new Date()); self.manageDebugLog("INFO_OS02", self.UNIQUEID, self.SID, "", 1, self.IS_DEBUG); cb(); } @@ -2050,7 +2442,7 @@ class CommonFunctions { var self = this; try { if (!offlineData.mt || offlineData.mt == config.messageType.ack) { - delete offlineData.sid; // Temp code + // delete offlineData.sid; // Temp code //var uid = self.UNIQUEID; } else { //var uid = offlineData.d[0].id; @@ -2284,7 +2676,7 @@ class CommonFunctions { try { offlineDataResult['od'] = 1; // offlineDataResult['mt'] = config.; - self.sendDataOnAzureMQTT(offlineDataResult); + self.sendDataOnMQTT(offlineDataResult); var index = offDataObj.findIndex(obj => obj.t == offlineDataResult.t); if (index > -1) { @@ -2375,17 +2767,17 @@ class CommonFunctions { Output : It publish the data on cloud using broker connection Date : 2020-11-25 */ - mqttPublishData(mqttHost, sensorData) { - // console.log("CommonFunctions -> mqttPublishData -> sensorData", sensorData) + async mqttPublishData(mqttHost, sensorData) { var self = this; var cacheId = self.SID + "_" + self.UNIQUEID; var deviceSyncRes = cache.get(cacheId); var brokerConfiguration = deviceSyncRes.p; + let sysConnected = false; // self.offlineProcess(sensorData); // return false; - require('dns').resolve(mqttHost, function (err) { - if (err) { + sysConnected = await isOnline(); + if (!sysConnected) { if (sensorData.mt == 1) { setTimeout(() => { if (!self.SDK_OPTIONS.offlineStorage.offlineProcessDisabled) { @@ -2403,44 +2795,58 @@ class CommonFunctions { // console.log("brokerConfiguration.topics -> ", brokerConfiguration.topics); try { var pubTopic = ""; + var messageType = ""; // if(deviceSyncRes.p && self.SDK_OPTIONS.SDK_TYPE == "MQTT") // pubTopic = deviceSyncRes.p.topics.ack; // console.log("CommonFunctions -> mqttPublishData -> sensorData.mt", sensorData.mt) if (sensorData == "" && self.SDK_OPTIONS.SDK_TYPE == "MQTT") { sensorData = {"twin": "all"}; - pubTopic = config.twinResponsePubTopic; + pubTopic = config[self.SDK_OPTIONS.pf]?.twinResponsePubTopic; + if(self.SDK_OPTIONS.pf === "aws"){ + pubTopic = deviceSyncRes.p.topics.set.pubForAll; + } } else if (sensorData['od'] == 1) { pubTopic = brokerConfiguration.topics.od; } else if ((sensorData.mt || sensorData.mt == 0) && self.SDK_OPTIONS.SDK_TYPE == "MQTT") { switch (sensorData.mt) { case config.messageType.rpt: pubTopic = brokerConfiguration.topics.rpt; + messageType = "RPT" break; case config.messageType.flt: pubTopic = brokerConfiguration.topics.flt; + messageType = "FLT" break; case config.messageType.rptEdge: pubTopic = brokerConfiguration.topics.erpt; + messageType = "ERPT" break; case config.messageType.ruleMatchedEdge: pubTopic = brokerConfiguration.topics.erm; + messageType = "ERM" break; case config.messageType.deviceCommandAck: pubTopic = brokerConfiguration.topics.ack; + messageType = "CMD-ACK" break; case config.messageType.otaCommandAck: pubTopic = brokerConfiguration.topics.ack; + messageType = "OTA-ACK" break; case config.messageType.moduleCommandAck: pubTopic = brokerConfiguration.topics.ack; + messageType = "MOD-ACK" break; default: break; } } else if ((!sensorData.mt || sensorData.mt != 0) && self.SDK_OPTIONS.SDK_TYPE == "MQTT") { - pubTopic = config.twinPropertyPubTopic; + pubTopic = config[self.SDK_OPTIONS.pf]?.twinPropertyPubTopic; + if(self.SDK_OPTIONS.pf === "aws"){ + pubTopic = deviceSyncRes.p.topics.set.pub; + } // if("sid" in sensorData) // delete sensorData.sid; // Temp Data } @@ -2449,6 +2855,8 @@ class CommonFunctions { sensorData["pubTopic"] = pubTopic; } sensorData["cd"] = deviceSyncRes.meta.cd ? deviceSyncRes.meta.cd : undefined; + + console.log("\x1b[33m %s %s\x1b[0m", messageType, pubTopic); // console.log("sensorData === > ", self.SDK_OPTIONS.isDebug); self.BROKER_CLIENT.messagePublish(sensorData, function (response) { if (response.status) { @@ -2469,7 +2877,6 @@ class CommonFunctions { self.manageDebugLog("ERR_SD01", self.UNIQUEID, self.SID, err.message, 0, self.IS_DEBUG); } } - }); } /* @@ -2480,7 +2887,7 @@ class CommonFunctions { */ mqttSubscribeData(cb) { var self = this; - if (!self.IS_DEVICE_CONNECTED) { + // if (self.IS_DEVICE_CONNECTED) { self.CMD_CALLBACK = cb; // console.log("1.0.1 ==> ") self.BROKER_CLIENT.subscribeData(function (response) { @@ -2520,7 +2927,7 @@ class CommonFunctions { self.manageDebugLog("ERR_IN01", self.UNIQUEID, self.SID, response.message, 0, self.IS_DEBUG); } }) - } + // } } /* @@ -2553,7 +2960,6 @@ class CommonFunctions { clientId: brokerConfiguration.id, port: brokerConfiguration.p, username: brokerConfiguration.un, - // password: brokerConfiguration.pwd+"123132132", password: brokerConfiguration.pwd, rejectUnauthorized: false, // rejectUnauthorized: true, @@ -2562,6 +2968,10 @@ class CommonFunctions { // connectTimeout: 50000 // pingTimer: 10 }; + if(self.SDK_OPTIONS.pf === "aws"){ + delete mqttOption.username; + delete mqttOption.password; + } try { // console.log("mqttOption ==> ", mqttOption); var conObj = { @@ -2614,10 +3024,14 @@ class CommonFunctions { username: brokerConfiguration.un, key: fs.readFileSync(sdkOption.certificate.SSLKeyPath), cert: fs.readFileSync(sdkOption.certificate.SSLCertPath), - //ca: fs.readFileSync(sdkOption.certificate.SSLCaPath), - rejectUnauthorized: true, + ca: [fs.readFileSync(sdkOption.certificate.SSLCaPath)], + rejectUnauthorized: false, reconnecting: true }; + if(self.SDK_OPTIONS.pf === "aws"){ + delete mqttOption.username; + delete mqttOption.password; + } try { var conObj = { @@ -2673,14 +3087,20 @@ class CommonFunctions { self.manageDebugLog("INFO_IN05", uniqueId, sId, "", 1, self.IS_DEBUG); var mqttOption = { clientId: brokerConfiguration.id, + // protocolId: 'MQIsdp', // Or 'MQIsdp' in MQTT 3.1 and 5.0 + // protocolVersion: 5, // port: brokerConfiguration.p, //8883, username: brokerConfiguration.un, key: fs.readFileSync(sdkOption.certificate.SSLKeyPath), cert: fs.readFileSync(sdkOption.certificate.SSLCertPath), - //ca: fs.readFileSync(sdkOption.certificate.SSLCaPath), - rejectUnauthorized: true, + ca: [fs.readFileSync(sdkOption.certificate.SSLCaPath)], + rejectUnauthorized: false, reconnecting: true }; + if(self.SDK_OPTIONS.pf === "aws"){ + delete mqttOption.username; + delete mqttOption.password; + } try { var conObj = { "mqttUrl": mqttUrl, @@ -2714,7 +3134,6 @@ class CommonFunctions { self.manageDebugLog("ERR_IN13", uniqueId, sId, "", 0, self.IS_DEBUG); self.manageDebugLog("ERR_IN01", uniqueId, sId, error.message, 0, self.IS_DEBUG); } - cb(result); } else { self.manageDebugLog("ERR_IN11", uniqueId, sId, "", 0, self.IS_DEBUG); var result = { @@ -2733,48 +3152,79 @@ class CommonFunctions { } cb(result); } - } - } else if (self.SDK_OPTIONS.SDK_TYPE == "TPM") { - // console.log("========================= TPM connection ==================="); - self.BROKER_CLIENT.clientConnection(function (response) { - if (response.status) { - var result = { - status: true, - data: response.data, - message: "Connection Established" - } - cb(result); - } else { - var result = { - status: false, - data: null, - message: "Device connection failed" - } - cb(result); - } - }) - } else if (self.SDK_OPTIONS.SDK_TYPE == "AZURE") { - // console.log("Hello Az => ", self.SDK_OPTIONS); - // console.log("Hello Az => ", self.UNIQUEID); - // var conObj = {}; - self.BROKER_CLIENT.clientConnection(function (response) { - if (response.status) { - var result = { - status: true, - data: response.data, - message: "Connection Established" + } else if (authType == config.authType.CA_INDIVIDUAL) { + try { + if (brokerConfiguration) { + self.manageDebugLog("INFO_IN05", uniqueId, sId, "", 1, self.IS_DEBUG); + var mqttOption = { + clientId: brokerConfiguration.id, + // protocolId: 'MQIsdp', // Or 'MQIsdp' in MQTT 3.1 and 5.0 + // protocolVersion: 5, // + port: brokerConfiguration.p, //8883, + username: brokerConfiguration.un, + key: fs.readFileSync(sdkOption.certificate.SSLKeyPath), + cert: fs.readFileSync(sdkOption.certificate.SSLCertPath), + ca: [fs.readFileSync(sdkOption.certificate.SSLCaPath)], + rejectUnauthorized: false, + reconnecting: true + }; + if(self.SDK_OPTIONS.pf === "aws"){ + delete mqttOption.username; + delete mqttOption.password; + } + try { + var conObj = { + "mqttUrl": mqttUrl, + "mqttOption": mqttOption, + } + self.BROKER_CLIENT.clientConnection(conObj, function (response) { + // console.log("res ==> ", response); + if (response.status) { + var result = { + status: true, + data: { + "mqttClient": response.data, + "mqttClientId": brokerConfiguration.id + }, + message: "Connection Established" + } + } else { + var result = response; + } + cb(result); + }) + } catch (error) { + var result = { + status: false, + data: { + "mqttClient": null, + "mqttClientId": null + }, + message: error.message + } + self.manageDebugLog("ERR_IN13", uniqueId, sId, "", 0, self.IS_DEBUG); + self.manageDebugLog("ERR_IN01", uniqueId, sId, error.message, 0, self.IS_DEBUG); + } + } else { + self.manageDebugLog("ERR_IN11", uniqueId, sId, "", 0, self.IS_DEBUG); + var result = { + status: false, + data: null, + message: "Device connection failed" + } + cb(result); } - cb(result); - } else { + } catch (e) { + self.manageDebugLog("ERR_IN01", uniqueId, sId, e.message, 0, self.IS_DEBUG); var result = { status: false, - data: null, - message: "Device connection failed" + data: e, + message: "Invalid certificate file." } cb(result); } - }) - } + } + } } catch (error) { var result = { status: false, @@ -2849,7 +3299,7 @@ class CommonFunctions { } } ], function (err, response) { - if (newAttributeObj.length > 0 && newDeviceObj.length > 0) { + if (newAttributeObj?.length > 0 && newDeviceObj?.length > 0) { var sdkDataArray = []; async.forEachSeries(newDeviceObj, function (device, callbackdev) { var attArray = { @@ -3126,10 +3576,10 @@ class CommonFunctions { // }) // } } catch (error) { - self.manageDebugLog("ERR_SD01", uniqueId, sId, error.message, 0, self.IS_DEBUG); + self.manageDebugLog("ERR_SD01", self.UNIQUEID, self.SID ,error.message, 0, self.IS_DEBUG); callback({ status: false, - data: e.message, + data: error.message, message: "MQTT connection error" }) } @@ -3143,12 +3593,18 @@ class CommonFunctions { */ UpdateTwin(obj, callback) { var self = this; + var cacheId = self.SID + "_" + self.UNIQUEID; + var deviceSyncRes = cache.get(cacheId); + var brokerConfiguration = deviceSyncRes.p; try { // obj['sid'] = self.SID; if (obj) { if (self.SDK_OPTIONS.SDK_TYPE == "MQTT") { - //self.sendDataOnAzureMQTT(obj) - obj["pubTopic"] = config.twinPropertyPubTopic; + //self.sendDataOnMQTT(obj) + obj["pubTopic"] = config[self.SDK_OPTIONS.pf]?.twinPropertyPubTopic; + if(self.SDK_OPTIONS.pf === "aws"){ + obj["pubTopic"] = obj["pubTopic"].replace(/{Cpid_DeviceID}/g,`${brokerConfiguration.id}`); + } console.log("CommonFunctions -> UpdateTwin -> obj", obj) // delete obj.sid; self.BROKER_CLIENT.messagePublish(obj, function (response) { @@ -3164,8 +3620,6 @@ class CommonFunctions { self.BROKER_CLIENT.updateTwinProperty(obj, function (response) { callback(response) }); - } else if (self.SDK_OPTIONS.SDK_TYPE == "TPM") { - console.log("============== TPM twin Updtae =============="); } } else { callback({ @@ -3196,15 +3650,15 @@ class CommonFunctions { "dt": new Date(), "mt": msgType, "d": { - "ack": status.ack, + "ack": ackGuid, "type": cmdType, - //"st": status, - "st": msgType, - "msg": status.msg, + "st": status, + // "st": msgType, + "msg": msg, "cid": childId ? childId : null } } - self.sendDataOnAzureMQTT(obj); + self.sendDataOnMQTT(obj); callback({ status: true, data: null, @@ -3228,10 +3682,9 @@ class CommonFunctions { getAllTwins(callback) { var self = this; try { - // brokerClient.publish(config.twinResponsePubTopic, ""); if (self.SDK_OPTIONS.SDK_TYPE == "MQTT") { - // self.sendDataOnAzureMQTT(""); + self.sendDataOnMQTT(""); callback({ status: true, data: null, @@ -3241,8 +3694,6 @@ class CommonFunctions { self.BROKER_CLIENT.getTwinProperty(function (response) { callback(response) }); - } else if (self.SDK_OPTIONS.SDK_TYPE == "TPM") { - console.log("============== TPM twin Updtae ==============") } } catch (error) { callback({ @@ -3389,7 +3840,7 @@ class CommonFunctions { } /* - * Tpm device provisioning process + * * @author : MK * @param: */ diff --git a/iotconnect-sdk/config/config.js b/iotconnect-sdk/config/config.js index 5d2dec1..ac4c5c8 100644 --- a/iotconnect-sdk/config/config.js +++ b/iotconnect-sdk/config/config.js @@ -3,8 +3,9 @@ // const discoveryUrl = "/api/sdk/sid/<>/uid/<>"; const msgFormatVersion = "2.1"; const discoveryUrl = "/api/v"+msgFormatVersion+"/dsdk/sid/<>"; -const discoveryUrlHost = "https://discovery.iotconnect.io/"; -//const discoveryUrlHost = "http://52.204.155.38:219/"; //"http://10.81.234.124:7404"; +const discoveryUrlwithCpid = `/api/v${msgFormatVersion}/dsdk/cpid/<>/env/<>?pf=<>` +// const discoveryUrlHost = "https://discovery.iotconnect.io/"; +const discoveryUrlHost = "http://52.204.155.38:219/"; //"http://10.81.234.124:7404"; const sasTokenExpiryTime = 365 * 24 * 60; // (expiresInMins) Expiry time 365 days const dpsHostUrl = "global.azure-devices-provisioning.net"; const resyncFrequency = 10; // Recheck after 10 seconds @@ -18,6 +19,7 @@ const deviceParams = 204; const otaParams = 205; const protocolParams = 201; const allParams = 210; +const edgeFaultDataFrequency = 60000; // In 60 sec For Edge device only const hbStatusFlag = 0; const messageType = { @@ -206,7 +208,8 @@ const authType = { "CA_SIGNED" : 2, "CA_SELF_SIGNED" : 3, "TPM": 4, - "SYMMETRIC_KEY" : 5 + "SYMMETRIC_KEY" : 5, + "CA_INDIVIDUAL" : 7 } const msgType = { @@ -427,10 +430,18 @@ module.exports = { sdkVersion: "2.1", msgFormatVersion: msgFormatVersion, sdkLanguage: "M_Node", - twinPropertyPubTopic: "$iothub/twin/PATCH/properties/reported/?$rid=1", - twinPropertySubTopic: "$iothub/twin/PATCH/properties/desired/#", - twinResponsePubTopic: "$iothub/twin/GET/?$rid=0", - twinResponseSubTopic: "$iothub/twin/res/#", + az : { + twinPropertyPubTopic: "$iothub/twin/PATCH/properties/reported/?$rid=1", + twinPropertySubTopic: "$iothub/twin/PATCH/properties/desired/#", + twinResponsePubTopic: "$iothub/twin/GET/?$rid=0", + twinResponseSubTopic: "$iothub/twin/res/#", + }, + aws: { + twinPropertyPubTopic: "$aws/things/{Cpid_DeviceID}/shadow/name/{Cpid_DeviceID}_twin_shadow/report", + twinPropertySubTopic: "$aws/things/{Cpid_DeviceID}/shadow/name/{Cpid_DeviceID}_twin_shadow/property-shadow", + twinResponseSubTopic: "$aws/things/{Cpid_DeviceID}/shadow/name/{Cpid_DeviceID}_twin_shadow/get/all", + twinResponsePubTopic: "$aws/things/{Cpid_DeviceID}/shadow/name/{Cpid_DeviceID}_twin_shadow/get", + }, directMethodForSelectedMethodSubTopic_SW: "$iothub/methods/POST/{method_name}/?$rid={request_id}", directMethodForAllSubTopic_SW: "$iothub/methods/POST/#", errorLog: errorLog, @@ -446,5 +457,7 @@ module.exports = { createChildDeviceErrorCode: createChildDeviceErrorCode, deleteChildDeviceErrorCode: deleteChildDeviceErrorCode, commandTypeFlag: commandTypeFlag, - resyncFrequency: resyncFrequency + resyncFrequency: resyncFrequency, + discoveryUrlwithCpid, + edgeFaultDataFrequency } \ No newline at end of file diff --git a/iotconnect-sdk/src/az.js b/iotconnect-sdk/src/az.js deleted file mode 100644 index 54335ec..0000000 --- a/iotconnect-sdk/src/az.js +++ /dev/null @@ -1,1373 +0,0 @@ -var cache = require('memory-cache'); -var config = require('./../config/config'); -var fs = require('fs-extra'); -var async = require('async'); -var _ = require('lodash'); -var CommonFunctions = require("./../common/common"); - -class Az { - - constructor(connectionString, sId, sdkOptions = "", callback) { - this.commonLib = ""; - if (connectionString) { - this.CONNECTION_STRING = connectionString; - this.UNIQUE_ID = connectionString.split(";")[1].split("=")[1].split("-")[1]; - } else { - this.CONNECTION_STRING = ""; - this.UNIQUE_ID = ""; - } - - this.SID = sId; - this.LOG_PATH = "./logs/offline/" + sId + "_" + this.UNIQUE_ID + "/"; - this.CERT_PATH_FLAG = true; - this.DEVICE_CONNECTED = false; - this.STOP_SDK_CONNECTION = false; - this.HAS_ACTIVE_COUNT = 0; - this.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES = 0; - //set callback options - this.CONNECTION_STATUS_CALLBACK = ""; - this.TWIN_CHANGED_CALLBACK = ""; - this.DEVICE_CMD_CALLBACK = ""; - this.OTA_CMD_RECEIVED_CALLBACK = ""; - this.ATTRIBUTE_CHANGED_CALLBACK = ""; - this.DEVICE_CHANGED_CALLBACK = ""; - this.MODULE_RECEIVED_CALLBACK = ""; - let sdkOpt = {}; - sdkOpt['SDK_TYPE'] = "AZURE"; - sdkOpt['CONNECTION_STRING'] = this.CONNECTION_STRING; - - if (sdkOptions && 'debug' in sdkOptions) { - this.IS_DEBUG = sdkOptions.debug; - } else { - this.IS_DEBUG = false; // for Local testing true else false - } - sdkOpt['isDebug'] = this.IS_DEBUG; - sdkOpt['logPath'] = this.LOG_PATH; - - if (sdkOptions && 'certificate' in sdkOptions) { - let cert = { - "SSLKeyPath": (sdkOptions.certificate.SSLKeyPath && fs.existsSync(sdkOptions.certificate.SSLKeyPath)) ? sdkOptions.certificate.SSLKeyPath : this.CERT_PATH_FLAG = false, //<< SystemPath >>/key.pem", - "SSLCertPath": (sdkOptions.certificate.SSLCertPath && fs.existsSync(sdkOptions.certificate.SSLCertPath)) ? sdkOptions.certificate.SSLCertPath : this.CERT_PATH_FLAG = false, //"<< SystemPath >>/cert.pem", - "SSLCaPath": (sdkOptions.certificate.SSLCaPath && fs.existsSync(sdkOptions.certificate.SSLCaPath)) ? sdkOptions.certificate.SSLCaPath : this.CERT_PATH_FLAG = false //"<< SystemPath >>/ms.pem" - } - sdkOpt['certificate'] = cert; - } else { - this.CERT_PATH_FLAG = false; - } - - if (sdkOptions && 'offlineStorage' in sdkOptions) { - let offline = { - "disabled": (!sdkOptions.offlineStorage.disabled) ? false : sdkOptions.offlineStorage.disabled, //in MB default is FALSE - "availSpaceInMb": (!sdkOptions.offlineStorage.availSpaceInMb) ? 0 : sdkOptions.offlineStorage.availSpaceInMb, //in MB default is unlimited MB - "fileCount": (!sdkOptions.offlineStorage.fileCount || !sdkOptions.offlineStorage.availSpaceInMb) ? 1 : sdkOptions.offlineStorage.fileCount //Default fileCount is 1 - } - sdkOpt['offlineStorage'] = offline; - } else { - let offline = { - "disabled": false, //in MB default is FALSE - "availSpaceInMb": 0, //in MB default is unlimited MB - "fileCount": 1 //Default fileCount is 1 - } - sdkOpt['offlineStorage'] = offline; - } - let offlinePerFileDataLimit = eval(eval(sdkOpt.offlineStorage.availSpaceInMb * 1024) / sdkOpt.offlineStorage.fileCount); //Convert In KB - let offlineFileCount = sdkOpt.offlineStorage.fileCount; - let offlineProcessDisabled = sdkOpt.offlineStorage.disabled; - this.offlineFileConfig = { - "offlineProcessDisabled": offlineProcessDisabled, - "offlinePerFileDataLimit": offlinePerFileDataLimit, - "offlineFileCount": offlineFileCount - } - sdkOpt['offlineStorage'] = this.offlineFileConfig; - sdkOpt['isGatewayDevice'] = false; - sdkOpt['isEdgeDevice'] = false; - - this.commonLib = new CommonFunctions(sId, this.UNIQUE_ID, sdkOpt); - if (!connectionString) { - this.commonLib.manageDebugLog("ERR_IN05", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - } - if (!sId) { - this.commonLib.manageDebugLog("ERR_IN04", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - } - if (!this.UNIQUE_ID) { - this.commonLib.manageDebugLog("ERR_IN05", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - } - - this.SDK_OPTIONS = sdkOpt; - - if (sId && this.UNIQUE_ID) { - this.createPredefinedLogDirectories(); - this.init(function (response) { - callback(response) - }) - } - } - - async createPredefinedLogDirectories() { - var self = this; - var logPathBasUrlLogs = "./logs"; - var logPathBasUrlLogsOffline = "./logs/offline/"; - var debugPathBasUrl = "./logs/debug/"; - if (!fs.existsSync(logPathBasUrlLogs)) { - try { - fs.mkdirSync(logPathBasUrlLogs); - !fs.existsSync(logPathBasUrlLogsOffline) ? fs.mkdirSync(logPathBasUrlLogsOffline) : ""; - !fs.existsSync(debugPathBasUrl) ? fs.mkdirSync(debugPathBasUrl) : ""; - } catch (error) { - let logText = "\n[ERR_IN01] " + new Date().toUTCString() + " [" + self.SID + "_" + self.UNIQUE_ID + "] : " + error.message; - console.log(logText); - } - } - } - - /* - Module : Init Call - Author : Mayank [SOFTWEB] - Inputs : sId, uniqueId, sdkOption params - Output : Connected brokr client object - Date : 2018-01-24 - */ - async init(callback) { - var self = this; - var sId = self.SID; - var uniqueId = self.UNIQUE_ID; - var sdkOptions = self.SDK_OPTIONS; - if (sId && uniqueId) { - var sId = sId; - var uniqueId = uniqueId; - var LOG_PATH = self.LOG_PATH; - var newDevice = {}; - try { - var initData = { - "id" : self.UNIQUE_ID, - "sid" : self.SID, - "sdkOptions" : self.SDK_OPTIONS - } - if (!self.offlineFileConfig.offlineProcessDisabled) { - try { - if (!fs.existsSync(LOG_PATH)) { - fs.mkdirSync(LOG_PATH); - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN07", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message+555, 0, self.IS_DEBUG); - } - } - cache.put(self.SID + "_" + self.UNIQUE_ID, initData); - callback({ - status: true, - data: null, - message: "Init success" - }) - } catch (err) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, err.message+666, 0, self.IS_DEBUG); - callback({ - status: false, - data: err.message, - message: "Something went wrong." - }) - } - } else { - self.commonLib.manageDebugLog("ERR_IN15", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - callback({ - status: false, - data: [], - message: config.errorLog.ERR_IN15 - }) - } - } - - /* - Module : Get the device information - Author : Mayank [SOFTWEB] - Inputs : msgType - Output : Devie info - Date : 2020-01-06 - */ - getSyncDataByCommandType(msgType, callback) { - var self = this; - try { - // console.log("Az -> getSyncDataByCommandType -> msgType -> ", msgType) - - self.commonLib.getSyncData(msgType, function (response) { - if(response.status) { - callback({ - status: true, - data: null, - message: response.message - }) - } else { - callback({ - status: false, - data: null, - message: response.message - }) - } - }) - } catch (error) { - callback({ - status: false, - data: null, - message: error.message - }) - } - } - - /* - Module : Get Device Information - Author : Mayank [SOFTWEB] - Inputs : - Output : Devie info - Date : 2018-01-24 - */ - syncDevice(callback) { - var self = this; - try { - console.log("1.0.0 => "); - var initialParams = config.defaultParams; - self.getSyncDataByCommandType(config.msgType.allStatus, function(response){ - console.log(" response ==> ", response); - callback({ - status: response.status, - data: response.data, - message: response.message - }) - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - -/* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : - Output : Device connection - Date : 2020-12-31 - */ - connect() { - var self = this; - try { - self.deviceConnectionProcess(); - } catch (err) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } - - - /* - Module : Get Device Information - Author : Mayank [SOFTWEB] - Inputs : msgType - Output : Devie info - Date : 2018-01-24 - */ - // getSyncData(messageType) { - // try { - // this.commonLib.getSyncData(this.CLIENT_CONNECTION, this.UNIQUE_ID, this.CPID, this.offlineFileConfig, messageType, function (response) { - // console.log("Requested for device details."); - // }) - // } catch (error) { - // console.log("Get device detail error :: ", error.message) - // // callback({ - // // status: false, - // // data: error, - // // message: error.message - // // }) - // } - // } - - /* - Module : Device Connection process - Author : Mayank [SOFTWEB] - Inputs : - Output : Request for the value which have data - Date : 2021-02-02 - */ - reqDataForActiveProperty(resData) { - var self = this; - - try { - async.series([ - function(pcb){ - if(resData['d'] == 1){ - self.getSyncDataByCommandType(config.msgType.childDevice, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['attr'] == 1){ - self.getSyncDataByCommandType(config.msgType.attribute, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['set'] == 1){ - self.getSyncDataByCommandType(config.msgType.setting, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['r'] == 1){ - self.getSyncDataByCommandType(config.msgType.rule, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['ota'] == 1){ - self.getSyncDataByCommandType(config.msgType.ota, function(res){ - pcb(); - }); - } else { - pcb(); - } - } - ], - function(err, results){ }); - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Device Connection process - Author : Mayank [SOFTWEB] - Inputs : - Output : Global callback for command and other data - Date : 2020-04-13 - */ - deviceConnectionProcess() { - var self = this; - try { - self.clientConnection(function (clientResponse) { - if (clientResponse.status) { - self.DEVICE_CONNECTED = true; - self.STOP_SDK_CONNECTION = true; - self.startCommandSubscriber(function(response){ - if(response.status) { - var responseData = cache.get(self.SID + "_" + self.UNIQUE_ID); - if(responseData && "has" in responseData) { - self.reqDataForActiveProperty(responseData.has); - } else { // For Azure - setTimeout(() => { - self.getSyncDataByCommandType(config.msgType.allStatus, function(res){ - // console.log("all 200 request send => ",res); - }); - }, 3000); - } - } else { - self.commonLib.manageDebugLog("ERR_IN17", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - }); - } else { - self.commonLib.manageDebugLog("ERR_IN13", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - }) - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Client Connection - Author : Mayank [SOFTWEB] - Inputs : uniqueId, sdk Option params - Output : Connected brokr client object - Date : 2020-04-13 - */ - clientConnection(callback) { - var self = this; - try { - self.commonLib.clientConnection(function (response) { - callback({ - status: response.status, - data: response, - message: response.message - }) - }) - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - Module : Start Command subscriber - Author : Mayank [SOFTWEB] - Inputs : device client connection - Output : start listner - Date : 2018-01-24 - */ - startCommandSubscriber(callback) { - var self = this; - try { - self.commonLib.subscriberProcess(function (response) { - if (response.status) { - if(response.data.cmdReceiveType == "cmd"){ - if(!response.data.data.d) { - self.manageCommand(response.data); - } else { - self.manageDeviceInfo(response.data.data); - } - } - - if(response.data.cmdReceiveType == "twin"){ - if(self.TWIN_CHANGED_CALLBACK) - self.TWIN_CHANGED_CALLBACK(response.data.data); - } - } - }); - callback({ - status: true, - data: null, - message: "Devie subscription started." - }) - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : uniqueId, message from subscribed listener - Output : Manage Command - Date : 2020-04-13 - */ - manageCommand(response) { - var self = this; - var cmdType = response.data.ct; - var commandData = response.data; - - switch (response.data.ct) { - case config.commandType.CORE_COMMAND: //0 - Ok device - self.commonLib.manageDebugLog("INFO_CM01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = undefined; - if(self.DEVICE_CMD_CALLBACK) - self.DEVICE_CMD_CALLBACK(commandData); - break; - - case config.commandType.FIRMWARE_UPDATE: //1 - OTA Firmware update - self.commonLib.manageDebugLog("INFO_CM02", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = undefined; - if(self.OTA_CMD_RECEIVED_CALLBACK) - self.OTA_CMD_RECEIVED_CALLBACK(commandData); - break; - - case config.commandType.MODULE_COMMAND: //2 - Module command - self.commonLib.manageDebugLog("INFO_CM06", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = undefined; - if(self.MODULE_RECEIVED_CALLBACK) - self.MODULE_RECEIVED_CALLBACK(commandData); - break; - - case config.commandType.DEVICE_CONNECTION_STATUS: // 3 - Connection status true/false - - // console.log("Mqtt -> manageCommand -> data", commandData) - if(commandData.command) { - self.DEVICE_CONNECTED = true; - } else { - self.DEVICE_CONNECTED = false; - } - var requestedParams = undefined; - self.commonLib.manageDebugLog("INFO_CM09", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(self.CONNECTION_STATUS_CALLBACK) - self.CONNECTION_STATUS_CALLBACK(commandData); - break; - - case config.commandType.REFRESH_ATTRIBUTE: //101 - Attribute Changed - self.commonLib.manageDebugLog("INFO_CM03", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.attributeParams; - break; - - case config.commandType.REFRESH_SETTING_TWIN: //102 - Setting Changed - self.commonLib.manageDebugLog("INFO_CM04", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.settingsParams; - break; - - case config.commandType.REFRESH_EDGE_RULE: //103 - Rule Changed - self.commonLib.manageDebugLog("INFO_CM07", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.ruleParams; - break; - - case config.commandType.REFRESH_CHILD_DEVICE: //104 - Device Changed - self.commonLib.manageDebugLog("INFO_CM06", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.deviceParams; - break; - - case config.commandType.DATA_FREQUENCY_CHANGE: //105 - Data Frequency Updated - self.commonLib.manageDebugLog("INFO_CM18", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var deviceSyncResDf = cache.get(self.SID+"_"+self.UNIQUE_ID); - deviceSyncResDf.meta.df = commandData.df; - cache.put(self.SID+"_"+self.UNIQUE_ID, deviceSyncResDf); - var requestedParams = undefined; - break; - - case config.commandType.DEVICE_DELETED: //106 - Device Deleted - self.commonLib.manageDebugLog("INFO_CM21", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - // var requestedParams = config.deviceParams; - break; - - case config.commandType.DEVICE_DISABLED: //107 - Device Disabled - self.commonLib.manageDebugLog("INFO_CM22", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.deviceParams; - break; - - case config.commandType.DEVICE_RELEASED: //108 - Device Released - self.commonLib.manageDebugLog("INFO_CM23", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - // var requestedParams = config.deviceParams; - break; - - case config.commandType.STOP_OPERATION: //109 - STOP SDK CONNECTION - self.commonLib.manageDebugLog("INFO_CM08", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - self.disconnect(config.commandType.STOP_OPERATION); - var requestedParams = undefined; - break; - - case config.commandType.START_HEARTBEAT_DEVICE: //110 - Heartbeat Start - self.commonLib.manageDebugLog("INFO_CM24", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - // var requestedParams = undefined; - var deviceSyncResDf = cache.get(self.SID+"_"+self.UNIQUE_ID); - deviceSyncResDf.meta["hbf"] = commandData.f; - self.commonLib.heartBeatProcess(deviceSyncResDf.meta["hbf"], "START"); - cache.put(self.SID+"_"+self.UNIQUE_ID, deviceSyncResDf); - break; - - case config.commandType.STOP_HEARTBEAT_DEVICE: //111 - Heartbeat Stop - self.commonLib.manageDebugLog("INFO_CM25", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var deviceSyncResDf = cache.get(self.SID+"_"+self.UNIQUE_ID); - deviceSyncResDf.meta["hbf"] = null; - self.commonLib.heartBeatProcess(deviceSyncResDf.meta["hbf"], "STOP"); - cache.put(self.SID+"_"+self.UNIQUE_ID, deviceSyncResDf); - var requestedParams = undefined; - break; - - default: - break; - } - - if (requestedParams != "" && requestedParams != undefined) { - self.commonLib.syncDeviceOnDemand(requestedParams, cmdType, function (response) { - if (cmdType == config.commandType.PASSWORD_INFO_UPDATE) { - setTimeout(() => { - self.deviceConnectionProcess() - }, 3000); - } else { - self.startEdgeDeviceProcess(requestedParams); - } - }); - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : uniqueId, device data - Output : Manage Device information - Date : 2020-05-04 - */ - manageDeviceInfo(response) { - // console.log("Mqtt -> ********************** -> response", JSON.stringify(response)) - var self = this; - var ctStatus = response.d.ct; - var cacheId = self.SID+"_"+self.UNIQUE_ID; - - switch (ctStatus) { - case config.msgType.allStatus: //200 - All data - if (response.d.ec == 0 && response.d.ct == config.msgType.allStatus) { - response.d["id"] = self.UNIQUE_ID; - response.d["sid"] = self.SID; - if(response.d.meta && response.d.meta.edge == true) { - self.SDK_OPTIONS.isEdgeDevice = true; - } - if(response.d.meta && response.d.meta.gtw != null){ - response.d["d"] = [ { "tg": response.d.meta.gtw.tg, "id": self.UNIQUE_ID, "s": 0 } ] - // console.log(" In => ", response); - self.SDK_OPTIONS.isGatewayDevice = true; - } else { - response.d["d"] = [ { "id": self.UNIQUE_ID, "s": 0 } ] - self.SDK_OPTIONS.isGatewayDevice = false; - // console.log(" Out => ", response); - } - // if(deviceSyncRes.p && self.SDK_OPTIONS.SDK_TYPE == "MQTT") - // pubTopic = deviceSyncRes.p.topics.di; - var cacheData = cache.get(cacheId); - if(cacheData) { - cacheData.meta = response.d.meta; - cacheData['d'] = response.d["d"]; - if(self.SDK_OPTIONS.SDK_TYPE == "MQTT") { - var authType = cacheData.meta.at; - cacheData.meta['at'] = authType; - } - cacheData.has = response.d.has; - cache.put(cacheId, cacheData); - } else { - cache.put(cacheId, response.d); - } - - self.reqDataForActiveProperty(response.d.has); - self.attributeChangedCallbackProcess("d"); - self.commonLib.manageDebugLog("INFO_CM11", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - case config.msgType.attribute: //201 - attribute - if (response.d.ec == 0 && response.d.ct == config.msgType.attribute) { - var deviceData = cache.get(cacheId); - // console.log("Mqtt -> manageDeviceInfo -> deviceData", JSON.stringify(response.d['att']) ) - // console.log("Mqtt -> manageDeviceInfo -> self.SDK_OPTIONS.isEdgeDevice ", self.SDK_OPTIONS.isEdgeDevice) - deviceData["att"] = response.d['att']; - cache.put(cacheId, deviceData); - self.commonLib.manageDebugLog("INFO_CM12", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(self.SDK_OPTIONS.isEdgeDevice) - self.checkForEdgeDeviceConfigurationProcess("attr"); - self.attributeChangedCallbackProcess("attr"); - } - break; - - case config.msgType.setting: //202 - setting - if (response.d.ec == 0 && response.d.ct == config.msgType.setting) { - var deviceData = cache.get(cacheId); - deviceData["set"] = response.d['set']; - cache.put(cacheId, deviceData); - self.commonLib.manageDebugLog("INFO_CM13", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - case config.msgType.rule: //203 - rule - if (response.d.ec == 0 && response.d.ct == config.msgType.rule) { - var deviceData = cache.get(cacheId); - // console.log("Mqtt -> manageDeviceInfo -> response.d['r']", JSON.stringify(response.d['r']) ) - deviceData["r"] = response.d['r']; - cache.put(cacheId, deviceData); - self.commonLib.manageDebugLog("INFO_CM14", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - // console.log("Mqtt -> manageDeviceInfo -> response.d['r']", response.d['r']) - if(self.SDK_OPTIONS.isEdgeDevice) - self.checkForEdgeDeviceConfigurationProcess("r"); - } - break; - - case config.msgType.childDevice: //204 - childDevice - if (response.d.ec == 0 && response.d.ct == config.msgType.childDevice) { - var deviceData = cache.get(cacheId); - var devices = response.d['d']; - if(self.SDK_OPTIONS.isGatewayDevice){ - var gatewayDevice = [ { "tg": deviceData.meta.gtw.tg, "id": self.UNIQUE_ID } ]; - var result = _.unionWith(gatewayDevice, devices, _.isEqual); - deviceData["d"] = result; - if(self.SDK_OPTIONS.isEdgeDevice) - self.checkForEdgeDeviceConfigurationProcess("d"); - self.attributeChangedCallbackProcess("d"); - } else { - deviceData["d"] = response.d['d']; - } - cache.put(cacheId, deviceData); - self.commonLib.manageDebugLog("INFO_CM15", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - case config.msgType.ota: //205 - ota - if (response.d.ec == 0 && response.d.ct == config.msgType.ota) { - var deviceData = cache.get(cacheId); - deviceData["ota"] = response.d['ota']; - cache.put(cacheId, deviceData); - } - break; - - case config.msgType.all: //210 - All data - if (response.d.ec == 0 && response.d.ct == config.msgType.all) { - response.d["id"] = uniqueId; - response.d["cpId"] = self.SID; - // self.startEdgeDeviceProcess(); - self.commonLib.manageDebugLog("INFO_CM11", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(response.d.meta && response.d.meta.edge == true) { - self.SDK_OPTIONS.isEdgeDevice = true; - } - if(response.d.meta && response.d.meta.gtw){ - response.d["d"] = [ { "tg": response.d.meta.gtw.tg, "id": self.UNIQUE_ID, "s": 0 } ] - self.SDK_OPTIONS.isGatewayDevice = true; - } else { - response.d["d"] = [ { "id": self.UNIQUE_ID, "s": 0 } ] - self.SDK_OPTIONS.isGatewayDevice = false; - } - cache.put(cacheId, response.d); - // console.log("======= > ", cache.get(cacheId)); - // this.reqDataForActiveProperty(response.d.has); - // self.startEdgeDeviceProcess(); - self.attributeChangedCallbackProcess("d"); - self.attributeChangedCallbackProcess("r"); - self.attributeChangedCallbackProcess("att"); - if(self.SDK_OPTIONS.isEdgeDevice) { - self.checkForEdgeDeviceConfigurationProcess("d"); - self.checkForEdgeDeviceConfigurationProcess("att"); - self.checkForEdgeDeviceConfigurationProcess("r"); - } - } - break; - - case config.msgType.createChildDevice : //221 - Create child device response - if (response.d.ec == 0 && response.d.ct == config.msgType.createChildDevice) { - // response.d["id"] = uniqueId; - // response.d["cpId"] = self.SID; - // cache.put(cacheId, response.d); - // self.startEdgeDeviceProcess(); - self.commonLib.manageDebugLog("INFO_CM19", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - case config.msgType.deleteChildDevice : //222 - Create child device response - if (response.d.ec == 0 && response.d.ct == config.msgType.deleteChildDevice) { - // response.d["id"] = uniqueId; - // response.d["cpId"] = self.SID; - // cache.put(cacheId, response.d); - // self.startEdgeDeviceProcess(); - self.commonLib.manageDebugLog("INFO_CM20", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - default: // unknown command - break; - } - } - - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : - Output : Edge devie processing - Date : 2020-04-14 - */ - startEdgeDeviceProcess(requestedParams = "") { - var self = this; - var responseData = cache.get(self.SID + "_" + self.UNIQUE_ID); - if (responseData.meta.edge == config.edgeEnableStatus.enabled) { - async.series([ - function (cb_series) { - try { - self.commonLib.setEdgeConfiguration(responseData.att, responseData.d, function (res) { - if (res.status) { - responseData.edgeData = res.data.mainObj; - if ((requestedParams && requestedParams.attribute) || requestedParams == "") { - async.forEachSeries(res.data.intObj, function (data, cb_inner) { - self.commonLib.setIntervalForEdgeDevice(data.tumblingWindowTime, data.lastChar, data.edgeAttributeKey, data.uniqueId, data.attrTag, data.devices); - cb_inner(); - }, function () {}); - } - } - cb_series(); - }); - } catch (err) { - cb_series(); - } - }, - function (cb_series) { - try { - // console.log("responseData.r ==> ", responseData.r); - setTimeout(() => { - self.commonLib.setRuleaConfiguration(responseData.r, self.UNIQUE_ID, function (res) { - if (res.status) { - responseData.rulesData = res.data; - } else { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, res.message, 0, self.IS_DEBUG); - } - cb_series(); - }); - }, 500); - } catch (err) { - cb_series(); - } - } - ], function (err, response) { }) - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : uniqueId (Device serial number) - Output : Device detail with all attributes - Date : 2018-01-24 - */ - sendData(data) { - var self = this; - if (data != "" && data.length > 0 && typeof data == 'object') { - try { - // var dateTimeArray = data.filter(date => { - // if (self.checkDateObjFormat(date.time)) { - // return true; - // } else { - // return true; - // } - // }); - //dateTimeArray.length == data.length - if (self.STOP_SDK_CONNECTION && self.UNIQUE_ID == data[0].uniqueId) { - self.commonLib.SendDataToHub(data, function (response) { - if (response.status) {} - }) - } else { - if (self.UNIQUE_ID != data[0].uniqueId) { - self.commonLib.manageDebugLog("ERR_SD02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - // if (dateTimeArray.length != data.length) { - // self.commonLib.manageDebugLog("ERR_SD03", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - // } - if (self.STOP_SDK_CONNECTION == false) { - self.commonLib.manageDebugLog("ERR_SD04", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } catch (err) { - console.log(" err => ", err); - self.commonLib.manageDebugLog("ERR_SD01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } else { - if (!data) { - self.commonLib.manageDebugLog("ERR_SD06", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - if (typeof data != 'object') { - self.commonLib.manageDebugLog("ERR_SD05", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : - Output : Device detail with all atrributes - Date : 2018-04-06 - */ - getAttributes(callback) { - var self = this; - try { - self.commonLib.getAttributes(function (response) { - - // console.log("Az -> getAttributes -> response.status", JSON.stringify(response) ) - if (response.status) { - var sdkDataArray = []; - async.forEachSeries(response.data.device, function (device, callbackdev) { - var attArray = { - "device": { - "id": device.id, - "tg": device.tg == "" ? undefined : device.tg - }, - "attributes": [] - } - var attributeData = response.data.attribute; - async.forEachSeries(attributeData, function (attrib, callbackatt) { - if (attrib.p == "") // Parent - { - async.forEachSeries(attrib.d, function (att, cb_attr) { - if(self.SDK_OPTIONS.isGatewayDevice) { - if (att.tg == device.tg) - { - delete att.tg; - delete att.agt; - att.dt = dataTypeToString(att.dt) - attArray['attributes'].push(att); - } - } else { - if(att.agt) - delete att.agt - att.dt = dataTypeToString(att.dt) - attArray['attributes'].push(att); - } - cb_attr(); - }, function () { - callbackatt(); - }) - } else { // Parent-child - if(self.SDK_OPTIONS.isGatewayDevice) { - if (attrib.tg == device.tg) - { - if (attrib.p != "") { - delete attrib.agt; - var pcAttributes = { - "ln": attrib.p, - "dt": dataTypeToString(attrib.dt), - "tg": attrib.tg == "" ? undefined : attrib.tg, - "tw": attrib.tw == "" ? undefined : attrib.tw, - "d": [] - }; - } - async.forEachSeries(attrib.d, function (att, cb_attr) { - if (att.tg == device.tg) // Parent - { - var cAttribute = { - "ln": att.ln, - "dt": dataTypeToString(att.dt), - "dv": att.dv, - "tg": att.tg == "" ? undefined : att.tg, - "tw": att.tw == "" ? undefined : att.tw - } - pcAttributes.d.push(cAttribute) - } - cb_attr(); - }, function () { - attArray['attributes'].push(pcAttributes) - callbackatt(); - }) - } else { - callbackatt(); - } - } else { - if (attrib.p != "") { - delete attrib.agt; - var pcAttributes = { - "ln": attrib.p, - "dt": dataTypeToString(attrib.dt), - "tw": attrib.tw == "" ? undefined : attrib.tw, - "d": [] - }; - } - async.forEachSeries(attrib.d, function (att, cb_attr) { - var cAttribute = { - "ln": att.ln, - "dt": dataTypeToString(att.dt), - "dv": att.dv, - "tw": att.tw == "" ? undefined : att.tw - } - pcAttributes.d.push(cAttribute) - cb_attr(); - }, function () { - attArray['attributes'].push(pcAttributes) - callbackatt(); - }) - } - } - }, function () { - sdkDataArray.push(attArray); - callbackdev(); - }) - }, function () { - self.commonLib.manageDebugLog("INFO_GA01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - callback({ - status: true, - data: sdkDataArray, - message: "Attribute get successfully." - }); - }) - } else { - self.commonLib.manageDebugLog("ERR_GA02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - callback({ - status: false, - data: null, - message: "Attributes data not found" - }); - } - }) - } catch (err) { - console.log(err) - self.commonLib.manageDebugLog("ERR_GA01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: err, - message: err.message - }); - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : Key, Value - Output : Device list - Date : 2019-06-11 - */ - updateTwin(key, value) { - var self = this; - try { - if (self.STOP_SDK_CONNECTION == true && key && (value || value === null)) { - var obj = {}; - obj[key] = value; - obj['sid'] = self.SID; - self.commonLib.UpdateTwin(obj, function (response) { - if (response.status) { - self.commonLib.manageDebugLog("INFO_TP01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } else { - self.commonLib.manageDebugLog("ERR_TP01", self.UNIQUE_ID, self.SID, response.message, 0, self.IS_DEBUG); - } - }) - } else { - if (self.STOP_SDK_CONNECTION == false) { - self.commonLib.manageDebugLog("ERR_TP02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - if (!key || !value) { - self.commonLib.manageDebugLog("ERR_TP03", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } catch (err) { - self.commonLib.manageDebugLog("ERR_TP01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } - - - /* - Module : Device disconnect - Author : Mayank [SOFTWEB] - Inputs : uniqueID, client connection - Output : device disconnected message - Date : 2019-06-11 - */ - disconnect(hardStopCmd = "") { - var self = this; - try { - console.log("self.DEVICE_CONNECTED => ", self.DEVICE_CONNECTED); - if (self.DEVICE_CONNECTED) { - self.commonLib.disconnectDevice(function (response) { - if(response.status){ - self.DEVICE_CONNECTED = false; - if(hardStopCmd){ - self.STOP_SDK_CONNECTION = false; - self.commonLib.deleteAllLogFile(self.LOG_PATH); - } - } - }) - } else { - if (self.DEVICE_CONNECTED == false) { - self.commonLib.manageDebugLog("INFO_DC01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } else { - self.commonLib.manageDebugLog("ERR_DC02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_DC01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Send command ack - Author : Mayank [SOFTWEB] - Inputs : data, time and message type - Output : message - Date : 2020-03-11 - */ - sendAck(objdata, mt) { - var self = this; - try { - if (this.STOP_SDK_CONNECTION == true && objdata && typeof objdata == 'object' && mt) { - self.commonLib.sendCommandAck(objdata, mt, function (response) { - self.commonLib.manageDebugLog("INFO_CM10", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - }) - } else { - if (self.STOP_SDK_CONNECTION == false) { - self.commonLib.manageDebugLog("ERR_CM04", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - if (!objdata || !mt) { - self.commonLib.manageDebugLog("ERR_CM02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } else { - if (typeof objdata != "object") { - self.commonLib.manageDebugLog("ERR_CM03", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_CM01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : get all twins properties - Author : Mayank [SOFTWEB] - Inputs : - Output : publish message - Date : 2020-04-20 - */ - getAllTwins() { - var self = this; - try { - if (this.STOP_SDK_CONNECTION == true && self.DEVICE_CONNECTED == true ) { - self.commonLib.getAllTwins(function (response) { - self.commonLib.manageDebugLog("INFO_TP02", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - }) - } else { - self.commonLib.manageDebugLog("ERR_TP04", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_TP01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } - - async checkDateObjFormat(dateObj) { - if (Object.prototype.toString.call(dateObj) === "[object Date]") { - if (isNaN(dateObj.getTime())) { - return false; - } else { - return true; - } - } else { - return false; - } - } - - async setConnectionStatusChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.CONNECTION_STATUS_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM05", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setTwinChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.TWIN_CHANGED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM06", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setDeviceCommandCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.DEVICE_CMD_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM07", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - - } - } - - async setOTAReceivedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.OTA_CMD_RECEIVED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM08", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setAttributeChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.ATTRIBUTE_CHANGED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM09", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setDeviceChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.DEVICE_CHANGED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM10", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setModuleReceivedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.MODULE_RECEIVED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM11", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : deviceId, deviceTag, displayName - Output : Create Device - Date : 2021-09-13 - */ - async createChildDevice(deviceId, deviceTag, displayName, callback) { - var self = this; - try { - self.commonLib.createChildDevice(deviceId, deviceTag, displayName, function (response) { - callback(response) - }); - } catch (err) { - callback({ - status: false, - data: null, - message: err.message - }) - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : deviceId, deviceTag, displayName - Output : Delete Device - Date : 2021-09-13 - */ - async deleteChildDevice(deviceId, callback) { - var self = this; - try { - self.commonLib.deleteChildDevice(deviceId, function (response) { - callback(response) - }); - } catch (err) { - callback({ - status: false, - data: null, - message: err.message - }) - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : item key reference attr, d, r - Output : Call edge configuration after all required process done - Date : 2020-09-03 - */ - checkForEdgeDeviceConfigurationProcess(item){ - console.log("====> Mqtt -> item -> ", item) - var self = this; - var deviceData = cache.get(self.SID+"_"+self.UNIQUE_ID); - var hasItems = _.cloneDeep(deviceData.has); - - delete hasItems.ota; - delete hasItems.set; - if(!self.SDK_OPTIONS.isGatewayDevice) - delete hasItems.d; - - var tempArray = []; - _.filter(hasItems, function (o, index) { - if (o == true) { - tempArray.push(index) - } - }); - var hasCount = 0; - - if(tempArray.length > 0) { - hasCount = tempArray.length; - async.forEachSeries(tempArray, function (data, cb) { - if(item == data) { - self.HAS_ACTIVE_COUNT++; - } - cb(); - }, function () { - if(hasCount == self.HAS_ACTIVE_COUNT){ - self.HAS_ACTIVE_COUNT = 0; - self.startEdgeDeviceProcess(); - } - }); - } - } - - /* - Module : Attribute - Author : Mayank [SOFTWEB] - Inputs : item key reference attr, d, r - Output : Call attribute changed callback after all required process done - Date : 2020-09-03 - */ - attributeChangedCallbackProcess(item){ - var self = this; - var deviceData = cache.get(self.SID+"_"+self.UNIQUE_ID); - var hasItems = _.cloneDeep(deviceData.has); - // console.log("Az -> attributeChangedCallbackProcess -> hasItems", hasItems) - if(hasItems) { - delete hasItems.ota; - delete hasItems.set; - delete hasItems.r; - - var tempArray = []; - _.filter(hasItems, function (o, index) { - if (o == true) { - tempArray.push(index) - } - }); - var hasCount = 0; - - if(tempArray.length > 0) { - hasCount = tempArray.length; - async.forEachSeries(tempArray, function (data, cb) { - if(item == data) { - self.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES++; - } - cb(); - }, function () { - if(hasCount == self.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES){ - if(self.ATTRIBUTE_CHANGED_CALLBACK){ - self.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES = 0; - self.ATTRIBUTE_CHANGED_CALLBACK(deviceData.att); - } - } - }); - } - } - } -} - -function dataTypeToString(value) { - switch (value) { - case config.dataType.NON_OBJ: // 0 NON_OBJ - return "NON_OBJ"; - case config.dataType.INTEGER: // 1 INTEGER - return "INTEGER"; - case config.dataType.LONG: // 2 LONG - return "LONG"; - case config.dataType.DECIMAL: // 3 DECIMAL - return "DECIMAL"; - case config.dataType.STRING: // 4 STRING - return "STRING"; - case config.dataType.TIME: // 5 TIME - return "TIME"; - case config.dataType.DATE: // 6 DATE - return "DATE"; - case config.dataType.DATETIME: // 7 DATETIME - return "DATETIME"; - case config.dataType.BIT: // 8 BIT - return "BIT"; - case config.dataType.BOOLEAN: // 9 BOOLEAN - return "BOOLEAN"; - case config.dataType.LATLONG: // 10 LATLONG - return "LATLONG"; - case config.dataType.OBJECT: // 11 OBJECT - return "OBJECT"; - } -} - -function generateSasToken(resourceUri, signingKey, policyName, expiresInMins, callback) { - resourceUri = encodeURIComponent(resourceUri); - - // Set expiration in seconds - var expires = (Date.now() / 1000) + expiresInMins * 60; - expires = Math.ceil(expires); - var toSign = resourceUri + '\n' + expires; - - // Use crypto - var hmac = crypto.createHmac('sha256', Buffer.from(signingKey, 'base64')); - hmac.update(toSign); - var base64UriEncoded = encodeURIComponent(hmac.digest('base64')); - - // Construct authorization string - var token = "SharedAccessSignature sr=" + resourceUri + "&sig=" - + base64UriEncoded + "&se=" + expires; - if (policyName) token += "&skn="+policyName; - - callback(token); -}; - -module.exports = Az; \ No newline at end of file diff --git a/iotconnect-sdk/src/mqtt.js b/iotconnect-sdk/src/mqtt.js index d409f1d..fe9a7e8 100644 --- a/iotconnect-sdk/src/mqtt.js +++ b/iotconnect-sdk/src/mqtt.js @@ -30,13 +30,6 @@ class Mqtt { this.initCallback = callback; sdkOpt['SDK_TYPE'] = "MQTT"; - // For SYmmetric Key Auth type support - if(sdkOptions && 'devicePK' in sdkOptions) { - this.DEVICE_PRIMARY_KEY = sdkOptions.devicePK; - } else { - this.DEVICE_PRIMARY_KEY = ""; - } - if(sdkOptions && 'skipValidation' in sdkOptions) { this.SKIP_VALIDATION = sdkOptions.skipValidation; } else { @@ -95,8 +88,19 @@ class Mqtt { sdkOpt['offlineStorage'] = this.offlineFileConfig; sdkOpt['isGatewayDevice'] = false; sdkOpt['isEdgeDevice'] = false; - this.LOG_PATH = "./logs/offline/" + sId + "_" + uniqueId + "/"; + this.LOG_PATH = "./logs/offline/" + (sId || sdkOptions.cpId) + "_" + uniqueId + "/"; sdkOpt['logPath'] = this.LOG_PATH; + sdkOpt['cpId'] = sdkOptions.cpId; + sdkOpt['env'] = sdkOptions.env; + sdkOpt['pf'] = sdkOptions.pf; + + this.commonLib = new CommonFunctions(sId, uniqueId, sdkOpt); + if (!sId) { + this.commonLib.manageDebugLog("ERR_IN04", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); + } + if (!uniqueId) { + this.commonLib.manageDebugLog("ERR_IN05", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); + } if (sdkOptions && 'discoveryURL' in sdkOptions && this.commonLib) { if (sdkOptions.discoveryURL != "" && sdkOptions.discoveryURL != undefined && sdkOptions.discoveryURL != null) { @@ -115,15 +119,7 @@ class Mqtt { } this.SDK_OPTIONS = sdkOpt; - this.commonLib = new CommonFunctions(sId, uniqueId, sdkOpt); - if (!sId) { - this.commonLib.manageDebugLog("ERR_IN04", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - } - if (!uniqueId) { - this.commonLib.manageDebugLog("ERR_IN05", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - } - - if (sId && uniqueId && !sdkOpt.offlineStorage.offlineProcessDisabled) { + if ((sId || sdkOpt.cpId) && uniqueId && !sdkOpt.offlineStorage.offlineProcessDisabled) { var self = this; this.createPredefinedLogDirectories(); this.init(function (response) { @@ -165,7 +161,7 @@ class Mqtt { */ async init(callback) { var self = this; - var sId = self.SID; + var sId = self.SID || self.SDK_OPTIONS.cpId; var uniqueId = self.UNIQUE_ID; if (sId && uniqueId) { var sId = sId; @@ -175,7 +171,7 @@ class Mqtt { var syncData = ""; self.commonLib.manageDebugLog("INFO_IN04", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); self.syncDevice(function (response) { - console.log("==== 200 command ======", JSON.stringify(response,null,2)); + // console.log("==== 200 command ======", JSON.stringify(response,null,2)); syncData = response; if (response) { @@ -203,20 +199,9 @@ class Mqtt { self.commonLib.manageDebugLog("INFO_CM11", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); //console.log("Mqtt -> init -> response.data.meta.at", response.data.meta.at) - if ((response.data.meta.at == config.authType.CA_SIGNED || response.data.meta.at == config.authType.CA_SELF_SIGNED) && self.CERT_PATH_FLAG == false) { - // console.log("1232132 innn") + if ((response.data.meta.at == config.authType.CA_SIGNED || response.data.meta.at == config.authType.CA_SELF_SIGNED || response.data.meta.at == config.authType.CA_INDIVIDUAL) && self.CERT_PATH_FLAG == false) { self.commonLib.manageDebugLog("ERR_IN06", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG) //process.exit(); - } else { - console.log("1232132 config.authType.SYMMETRIC_KEY ==> ", config.authType.SYMMETRIC_KEY) - if (response.data.meta.at == config.authType.SYMMETRIC_KEY) { - var deviceSyncRes = cache.get(self.SID + "_" + self.UNIQUE_ID); - var brokerConfiguration = deviceSyncRes.p; - generateSasToken(brokerConfiguration.h, self.DEVICE_PRIMARY_KEY, null, config.sasTokenExpiryTime, function (sasToken) { - deviceSyncRes.p.pwd = sasToken; - cache.put(self.SID + "_" + self.UNIQUE_ID, deviceSyncRes); - }); - } } self.DEVICE_CONNECTED = false; async.series([ @@ -517,7 +502,7 @@ class Mqtt { try { self.clientConnection(function (clientResponse) { // console.log("Mqtt -> deviceConnectionProcess -> clientResponse 11111 ==> ", clientResponse) - if (clientResponse.status) { + if (clientResponse?.status) { self.DEVICE_CONNECTED = true; self.STOP_SDK_CONNECTION = true; self.startCommandSubscriber(function (response) { @@ -574,9 +559,9 @@ class Mqtt { try { self.commonLib.clientConnection(function (response) { callback({ - status: response.status, + status: response?.status, data: response, - message: response.message + message: response?.message }) }) } catch (error) { @@ -663,6 +648,13 @@ class Mqtt { } } + dispose () { + var self = this; + self.commonLib.onHardStopCommand(); + console.log("DeviceId ::: [" + self.UNIQUE_ID + "] :: SDK Disconnected :: ", new Date()); + process.exit(); + } + /* Object : Device Author : Mayank [SOFTWEB] @@ -674,10 +666,12 @@ class Mqtt { var self = this; var cmdType = response.data.ct; var commandData = response.data; + var commandDataJson = commandData ? JSON.stringify(commandData) : "" switch (response.data.ct) { case config.commandType.CORE_COMMAND: //0 - Ok device self.commonLib.manageDebugLog("INFO_CM01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM01", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = undefined; if (self.DEVICE_CMD_CALLBACK) self.DEVICE_CMD_CALLBACK(commandData); @@ -685,13 +679,17 @@ class Mqtt { case config.commandType.FIRMWARE_UPDATE: //1 - OTA Firmware update self.commonLib.manageDebugLog("INFO_CM02", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM02", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = undefined; if (self.OTA_CMD_RECEIVED_CALLBACK) - self.OTA_CMD_RECEIVED_CALLBACK(commandData); + setTimeout(()=>{ + self.OTA_CMD_RECEIVED_CALLBACK(commandData); + }, 10000) break; case config.commandType.MODULE_COMMAND: //2 - Module command self.commonLib.manageDebugLog("INFO_CM05", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM05", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = undefined; if (self.MODULE_RECEIVED_CALLBACK) self.MODULE_RECEIVED_CALLBACK(commandData); @@ -705,27 +703,32 @@ class Mqtt { } var requestedParams = undefined; self.commonLib.manageDebugLog("INFO_CM09", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM09", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); if (self.CONNECTION_STATUS_CALLBACK) self.CONNECTION_STATUS_CALLBACK(commandData); break; case config.commandType.REFRESH_ATTRIBUTE: //101 - Attribute Changed self.commonLib.manageDebugLog("INFO_CM03", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM03", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = config.attributeParams; break; case config.commandType.REFRESH_SETTING_TWIN: //102 - Setting Changed self.commonLib.manageDebugLog("INFO_CM04", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM04", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = config.settingsParams; break; case config.commandType.REFRESH_EDGE_RULE: //103 - Rule Changed self.commonLib.manageDebugLog("INFO_CM07", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM07", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = config.ruleParams; break; case config.commandType.REFRESH_CHILD_DEVICE: //104 - Device Changed self.commonLib.manageDebugLog("INFO_CM06", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM06", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); if(self.SDK_OPTIONS.isGatewayDevice) { var requestedParams = config.deviceParams; } else { @@ -735,6 +738,7 @@ class Mqtt { case config.commandType.DATA_FREQUENCY_CHANGE: //105 - Data Frequency Updated self.commonLib.manageDebugLog("INFO_CM18", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM18", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var deviceSyncResDf = cache.get(self.SID + "_" + self.UNIQUE_ID); deviceSyncResDf.meta.df = commandData.df; cache.put(self.SID + "_" + self.UNIQUE_ID, deviceSyncResDf); @@ -746,6 +750,7 @@ class Mqtt { self.STOP_SDK_CONNECTION = false; var requestedParams = undefined; self.commonLib.manageDebugLog("INFO_CM21", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM21", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); break; case config.commandType.DEVICE_DISABLED: //107 - Device Disabled @@ -753,17 +758,20 @@ class Mqtt { self.STOP_SDK_CONNECTION = false; var requestedParams = config.deviceParams; self.commonLib.manageDebugLog("INFO_CM22", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM22", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); break; case config.commandType.DEVICE_RELEASED: //108 - Device Released self.commonLib.onHardStopCommand(); self.STOP_SDK_CONNECTION = false; self.commonLib.manageDebugLog("INFO_CM23", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM23", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = undefined; break; case config.commandType.STOP_OPERATION: //109 - STOP SDK CONNECTION self.commonLib.manageDebugLog("INFO_CM08", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM08", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); // self.disconnect(config.commandType.STOP_OPERATION); self.commonLib.onHardStopCommand(); self.STOP_SDK_CONNECTION = false; @@ -772,6 +780,7 @@ class Mqtt { case config.commandType.START_HEARTBEAT_DEVICE: //110 - Heartbeat Start self.commonLib.manageDebugLog("INFO_CM24", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM24", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var requestedParams = undefined; var deviceSyncResDf = cache.get(self.SID + "_" + self.UNIQUE_ID); deviceSyncResDf.meta["hbf"] = commandData.f; @@ -781,6 +790,7 @@ class Mqtt { case config.commandType.STOP_HEARTBEAT_DEVICE: //111 - Heartbeat Stop self.commonLib.manageDebugLog("INFO_CM25", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM25", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); var deviceSyncResDf = cache.get(self.SID + "_" + self.UNIQUE_ID); deviceSyncResDf.meta["hbf"] = null; self.commonLib.onHeartbeatCommand(false, 0); @@ -790,6 +800,7 @@ class Mqtt { case config.commandType.SDK_LOG_FLAG: //112 - SDK LOG ENABLED/DISABLED - Update flag SDK log display in cmd prompt self.commonLib.manageDebugLog("INFO_CM26", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM26", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); self.SDK_OPTIONS.isDebug = commandData.debugFlag; self.IS_DEBUG = commandData.debugFlag; self.commonLib.onLogCommand(commandData); @@ -798,6 +809,7 @@ class Mqtt { case config.commandType.SKIP_ATTRIBUTE_VALIDATION: //113 - SKIP ATTRIBUTE VALIDATION - Skip Attribute validation during data send self.commonLib.manageDebugLog("INFO_CM27", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM27", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); self.SDK_OPTIONS.skipValidation = commandData.skipValidation; self.commonLib.onValidationSkipCommand(commandData); var requestedParams = undefined; @@ -805,12 +817,14 @@ class Mqtt { case config.commandType.SEND_SDK_LOG_FILE: //114 - SEND SDK LOG FILE - Request command for SDK Log file upload self.commonLib.manageDebugLog("INFO_CM28", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM28", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); console.log(" Remain to be develope send SDK log file feature"); var requestedParams = undefined; break; case config.commandType.DEVICE_DELETE_REQUEST: //115 - DELETE DEVICE - Delete device request command self.commonLib.manageDebugLog("INFO_CM29", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); + self.commonLib.manageDebugLog("INFO_CM29", self.UNIQUE_ID, self.SID, commandDataJson, 1, self.IS_DEBUG); console.log(" Remain to be develope delete device feature"); var requestedParams = undefined; break; @@ -954,7 +968,7 @@ class Mqtt { var deviceData = cache.get(cacheId); deviceData["att"] = response.d['att']; cache.put(cacheId, deviceData); - console.log("Attribute Received ===>>>", JSON.stringify(deviceData.att, null, 2)) + console.log("Attribute Received ===>>>", JSON.stringify(response, null, 2)) self.commonLib.manageDebugLog("INFO_CM12", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); if (self.SDK_OPTIONS.isEdgeDevice) self.checkForEdgeDeviceConfigurationProcess("attr"); @@ -967,7 +981,7 @@ class Mqtt { var deviceData = cache.get(cacheId); deviceData["set"] = response.d['set']; cache.put(cacheId, deviceData); - console.log("Device setting >>>>>",JSON.stringify(deviceData.set, null, 2)); + console.log("Device setting >>>>>",JSON.stringify(response, null, 2)); self.commonLib.manageDebugLog("INFO_CM13", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); } break; @@ -996,11 +1010,12 @@ class Mqtt { }]; var result = _.unionWith(gatewayDevice, devices, _.isEqual); deviceData["d"] = result; + deviceData["has"]["d"] = result.length - 1; if(self.DEVICE_CHANGED_CALLBACK) self.DEVICE_CHANGED_CALLBACK(deviceData["d"]); if (self.SDK_OPTIONS.isEdgeDevice) - self.checkForEdgeDeviceConfigurationProcess("d"); - self.attributeChangedCallbackProcess("d"); + self.checkForEdgeDeviceConfigurationProcess("d", true); + self.attributeChangedCallbackProcess("d", true); } else { deviceData["d"] = response.d['d']; } @@ -1222,6 +1237,7 @@ class Mqtt { var obj = {}; obj[key] = value; // obj['sid'] = self.SID; + console.log("Shadow update received :::::",JSON.stringify(obj)); self.commonLib.UpdateTwin(obj, function (response) { if (response.status) { self.commonLib.manageDebugLog("INFO_TP01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); @@ -1601,7 +1617,7 @@ class Mqtt { Output : Call edge configuration after all required process done Date : 2020-09-03 */ - checkForEdgeDeviceConfigurationProcess(item) { + checkForEdgeDeviceConfigurationProcess(item, deviceChanged) { var self = this; var deviceData = cache.get(self.SID + "_" + self.UNIQUE_ID); var hasItems = _.cloneDeep(deviceData.has); @@ -1619,6 +1635,7 @@ class Mqtt { }); var hasCount = 0; + if (tempArray.length > 0) { hasCount = tempArray.length; async.forEachSeries(tempArray, function (data, cb) { @@ -1627,7 +1644,7 @@ class Mqtt { } cb(); }, function () { - if (hasCount == self.HAS_ACTIVE_COUNT) { + if (hasCount == self.HAS_ACTIVE_COUNT || deviceChanged) { self.HAS_ACTIVE_COUNT = 0; self.startEdgeDeviceProcess(); } @@ -1642,7 +1659,7 @@ class Mqtt { Output : Call attribute changed callback after all required process done Date : 2020-09-03 */ - attributeChangedCallbackProcess(item) { + attributeChangedCallbackProcess(item, deviceChanged) { var self = this; var deviceData = cache.get(self.SID + "_" + self.UNIQUE_ID); var hasItems = _.cloneDeep(deviceData.has); @@ -1667,7 +1684,7 @@ class Mqtt { } cb(); }, function () { - if (hasCount == self.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES) { + if (hasCount == self.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES || deviceChanged) { if (self.ATTRIBUTE_CHANGED_CALLBACK) { self.HAS_ACTIVE_COUNT_ATTRIBUTE_CHANGES = 0; self.ATTRIBUTE_CHANGED_CALLBACK(deviceData.att); diff --git a/iotconnect-sdk/src/tpm.js b/iotconnect-sdk/src/tpm.js deleted file mode 100644 index 37e2828..0000000 --- a/iotconnect-sdk/src/tpm.js +++ /dev/null @@ -1,1330 +0,0 @@ -var cache = require('memory-cache'); -var config = require('./../config/config'); -var fs = require('fs-extra'); -var async = require('async'); -var CommonFunctions = require("./../common/common"); - -class Tpm { - //constructor(cpid, this.UNIQUE_ID, messageCallback, twinCallback, sdkOptions = "", env = "") { - constructor(uniqueId, sId, scopeId, sdkOptions = "", getSecretCallback, callback) { - this.commonLib = ""; - this.UNIQUE_ID = uniqueId; - this.SID = sId; - this.DEVICE_CONNECTED = false; - this.STOP_SDK_CONNECTION = false; - this.ATTR_ACTIVE = false; - this.RULE_ACTIVE = false; - this.DEVICE_ACTIVE = false; - - //set callback options - this.CONNECTION_STATUS_CALLBACK = ""; - this.TWIN_CHANGED_CALLBACK = ""; - this.DEVICE_CMD_CALLBACK = ""; - this.OTA_CMD_RECEIVED_CALLBACK = ""; - this.ATTRIBUTE_CHANGED_CALLBACK = ""; - this.DEVICE_CHANGED_CALLBACK = ""; - this.MODULE_RECEIVED_CALLBACK = ""; - this.REQUEST_FOR_SECRET_CONFIGURATION = ""; - let sdkOpt = {}; - sdkOpt['SDK_TYPE'] = "TPM"; - - if(sdkOptions && 'isSimulatedTPMDevice' in sdkOptions) { - this.IS_TPM_SIMULATOR_AUTH = sdkOptions.isSimulatedTPMDevice; - } else { - this.IS_TPM_SIMULATOR_AUTH = false; // for Local testing true else false - } - - if (sdkOptions && 'dpsHost' in sdkOptions) { - if (sdkOptions.dpsHost != "" && sdkOptions.dpsHost != undefined && sdkOptions.dpsHost != null) { - this.DPS_PROVISIONING_HOST_URL = sdkOptions.dpsHost; - } else { - this.DPS_PROVISIONING_HOST_URL = config.dpsHostUrl; - } - } else { - this.DPS_PROVISIONING_HOST_URL = config.dpsHostUrl; - } - - if (sdkOptions && 'devicePrefix' in sdkOptions) { - this.DEVICE_PREFIX = sdkOptions.devicePrefifvx; - } else { - this.DEVICE_PREFIX = true; // Default value - } - - if (sdkOptions && 'azureIotEdgeDevice' in sdkOptions) { - this.AZURE_IOT_EDGE_DEVICE = sdkOptions.azureIotEdgeDevice; - } else { - this.AZURE_IOT_EDGE_DEVICE = false; // Default value - } - - sdkOpt['TPM'] = { - "IS_SIMULATED_TPM_DEVICE" : this.IS_TPM_SIMULATOR_AUTH, - "TPM_DEVICE_REGISTRATION_ID" : this.SID.substr(0, 43)+'-'+this.UNIQUE_ID, - "TPM_INITIAL_TWIN_SID" : this.SID.substr(0, 43), - "SCOPE_ID" : "", - "IS_TPM_DEVICE" : true, - "DPS_PROVISIONING_HOST_URL" : this.DPS_PROVISIONING_HOST_URL, - "SID_TPM_VERSION" : "1", - "DEVICE_PREFIX" : this.DEVICE_PREFIX, - "AZURE_IOT_EDGE_DEVICE" : this.AZURE_IOT_EDGE_DEVICE, - "DEVICE_REGISTRATION_ID": this.DEVICE_PREFIX == true ? this.UNIQUE_ID : this.SID.substr(0, 43)+'-'+this.UNIQUE_ID - } - - /** getSecret Logic */ - var dpsCs = getSecretCallback("DPSCS"); - var ekey = getSecretCallback("EKEY"); - var iotHubHost = getSecretCallback("IOTHUB"); - - sdkOpt['TPM']['DPS_CONNECTION_STRING'] = dpsCs ? dpsCs : ""; - sdkOpt['TPM']['ENDORCEMENT_KEY'] = ekey ? ekey : ""; - sdkOpt['TPM']['IOTHUB_HOST_NAME'] = iotHubHost ? iotHubHost : ""; - /** getSecret Logic */ - - if (sdkOptions && 'debug' in sdkOptions) { - this.IS_DEBUG = sdkOptions.debug; - } else { - this.IS_DEBUG = false; // for Local testing true else false - } - sdkOpt['isDebug'] = this.IS_DEBUG; - this.LOG_PATH = "./logs/offline/" + sId + "_" + this.UNIQUE_ID + "/"; - sdkOpt['logPath'] = this.LOG_PATH; - - if (sdkOptions && 'offlineStorage' in sdkOptions) { - let offline = { - "disabled": (!sdkOptions.offlineStorage.disabled) ? false : sdkOptions.offlineStorage.disabled, //in MB default is FALSE - "availSpaceInMb": (!sdkOptions.offlineStorage.availSpaceInMb) ? 0 : sdkOptions.offlineStorage.availSpaceInMb, //in MB default is unlimited MB - "fileCount": (!sdkOptions.offlineStorage.fileCount || !sdkOptions.offlineStorage.availSpaceInMb) ? 1 : sdkOptions.offlineStorage.fileCount //Default fileCount is 1 - } - sdkOpt['offlineStorage'] = offline; - } else { - let offline = { - "disabled": false, //in MB default is FALSE - "availSpaceInMb": 0, //in MB default is unlimited MB - "fileCount": 1 //Default fileCount is 1 - } - sdkOpt['offlineStorage'] = offline; - } - let offlinePerFileDataLimit = eval(eval(sdkOpt.offlineStorage.availSpaceInMb * 1024) / sdkOpt.offlineStorage.fileCount); //Convert In KB - let offlineFileCount = sdkOpt.offlineStorage.fileCount; - let offlineProcessDisabled = sdkOpt.offlineStorage.disabled; - this.offlineFileConfig = { - "offlineProcessDisabled": offlineProcessDisabled, - "offlinePerFileDataLimit": offlinePerFileDataLimit, - "offlineFileCount": offlineFileCount - } - sdkOpt['offlineStorage'] = this.offlineFileConfig; - sdkOpt['isGatewayDevice'] = false; - if(scopeId) { - sdkOpt['SCOPE_ID'] = scopeId; - } else { - sdkOpt['SCOPE_ID'] = ""; - } - - this.commonLib = new CommonFunctions(sId, this.UNIQUE_ID, sdkOpt); - if(!sdkOpt['SCOPE_ID']) { - this.commonLib.manageDebugLog("ERR_IN16", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - process.exit(); - } - if (!sId) { - this.commonLib.manageDebugLog("ERR_IN04", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - process.exit(); - } - if (!this.UNIQUE_ID) { - this.commonLib.manageDebugLog("ERR_IN05", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - process.exit(); - } - - if (!sdkOpt['TPM']['DPS_CONNECTION_STRING']) { - this.commonLib.manageDebugLog("ERR_IN18", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - process.exit(); - } - if (!sdkOpt['TPM']['ENDORCEMENT_KEY']) { - this.commonLib.manageDebugLog("ERR_IN19", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - process.exit(); - } - if (!sdkOpt['TPM']['IOTHUB_HOST_NAME']) { - this.commonLib.manageDebugLog("ERR_IN20", this.UNIQUE_ID, this.SID, "", 0, this.IS_DEBUG); - // process.exit(); - } - - this.SDK_OPTIONS = sdkOpt; - - // console.log("this.SDK_OPTIONS => ", this.SDK_OPTIONS); - // return false; - - if (sId && this.UNIQUE_ID) { - this.createPredefinedLogDirectories(); - this.init(function (response) { - callback(response) - }) - } - } - - async getDetail(arg, getSecretCallback){ - return getSecretCallback(arg); - } - - async createPredefinedLogDirectories() { - var self = this; - var logPathBasUrlLogs = "./logs"; - var logPathBasUrlLogsOffline = "./logs/offline/"; - var debugPathBasUrl = "./logs/debug/"; - if (!fs.existsSync(logPathBasUrlLogs)) { - try { - fs.mkdirSync(logPathBasUrlLogs); - !fs.existsSync(logPathBasUrlLogsOffline) ? fs.mkdirSync(logPathBasUrlLogsOffline) : ""; - !fs.existsSync(debugPathBasUrl) ? fs.mkdirSync(debugPathBasUrl) : ""; - } catch (error) { - let logText = "\n[ERR_IN01] " + new Date().toUTCString() + " [" + self.SID + "_" + self.UNIQUE_ID + "] : " + error.message; - console.log(logText); - } - } - } - - /* - Module : Init Call - Author : Mayank [SOFTWEB] - Inputs : sId, uniqueId, sdkOption params - Output : Connected brokr client object - Date : 2018-01-24 - */ - async init(callback) { - var self = this; - var sId = self.SID; - var uniqueId = self.UNIQUE_ID; - var sdkOptions = self.SDK_OPTIONS; - if (sId && uniqueId) { - var sId = sId; - var uniqueId = uniqueId; - var LOG_PATH = self.LOG_PATH; - try { - var initData = { - "id" : self.UNIQUE_ID, - "sid" : self.SID - } - if (!self.offlineFileConfig.offlineProcessDisabled) { - try { - if (!fs.existsSync(LOG_PATH)) { - fs.mkdirSync(LOG_PATH); - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN07", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - cache.put(self.SID + "_" + self.UNIQUE_ID, initData); - - // Logic to enroll and provisioning of the device - - async.series([ - function(enrollmentCB){ - console.log("In device Enrolling.."); - try { - self.deviceEnrollment(function (response) { - enrollmentCB(null, response); - }) - } catch (error) { - enrollmentCB(null, null); - } - }, - function(enrollmentCB){ - console.log("In Provisioning"); - try { - self.deviceDPSProvisioning(function (response) { - enrollmentCB(null, response); - }) - } catch (error) { - enrollmentCB(null, null); - } - }, - ], - function(err, results){ - if(results.length > 0) { - callback({ - status: true, - data: null, - message: "Init success" - }) - } else { - callback({ - status: false, - data: null, - message: "Init failed" - }) - } - // console.log("results => ", results); - }); - - } catch (err) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: err.message, - message: "Something went wrong." - }) - } - } else { - self.commonLib.manageDebugLog("ERR_IN15", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - callback({ - status: false, - data: [], - message: config.errorLog.ERR_IN15 - }) - } - } - - /* - Module : Get the device information - Author : Mayank [SOFTWEB] - Inputs : msgType - Output : Devie info - Date : 2020-01-06 - */ - getSyncDataByCommandType(msgType, callback) { - var self = this; - try { - self.commonLib.getSyncData(msgType, function (response) { - if(response.status) { - callback({ - status: true, - data: null, - message: response.message - }) - } else { - callback({ - status: false, - data: null, - message: response.message - }) - } - }) - } catch (error) { - callback({ - status: false, - data: null, - message: error.message - }) - } - } - - /* - Module : Get Device Information - Author : Mayank [SOFTWEB] - Inputs : - Output : Devie info - Date : 2018-01-24 - */ - syncDevice(callback) { - var self = this; - try { - var initialParams = config.defaultParams; - self.getSyncDataByCommandType(config.msgType.allStatus, function(response){ - // pcb(); - console.log(" response ==> ", response); - callback({ - status: response.status, - data: response.data, - message: response.message - }) - }); - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - -/* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : - Output : Device connection - Date : 2020-12-31 - */ - async connect() { - var self = this; - try { - - if(!self.DEVICE_CONNECTED) { - self.deviceConnectionProcess(); - } else { - self.commonLib.manageDebugLog("ERR_TP06", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - - // // self.deviceConnectionProcess(); - // async.waterfall([ - // function(cb_waterfall) { - // self.deviceEnrollment(function (response) { - // // console.log("Device Enrollment process done => ", response.status); - // cb_waterfall(null, response); - // }) - // // } else { - // // cb_waterfall(null, { - // // status: false, - // // data: null, - // // message: config.errorLog.ERR_IN18 - // // }) - // // } - // } - // ], function (err, result) { - // if(result.status) { - // self.deviceDPSProvisioning(function (response) { - // // console.log("Device provisioning process done => ", response); - // if(response.status) { - // self.deviceConnectionProcess(); - // } - // }) - // } else { - // self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, result.message, 0, self.IS_DEBUG); - // } - // }); - } catch (err) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Device Connection process - Author : Mayank [SOFTWEB] - Inputs : - Output : Device enrollment process response - Date : 2020-04-13 - */ - deviceEnrollment(callback) { - var self = this; - try { - // callback(true); - self.commonLib.deviceEnrollment(function (response) { - if(response.status) { - self.commonLib.manageDebugLog("INFO_IN16", self.UNIQUE_ID, self.SID, response.message, 1, self.IS_DEBUG); - callback(response) - } else { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, response.message, 0, self.IS_DEBUG); - callback(response) - } - }) - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - - /* - Module : Device Connection process - Author : Mayank [SOFTWEB] - Inputs : - Output : Device provisioning response - Date : 2020-04-13 - */ - deviceDPSProvisioning(callback) { - var self = this; - try { - self.commonLib.deviceDPSProvisioning(function (response) { - if(response.status) { - self.commonLib.manageDebugLog("INFO_IN17", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - callback(response) - } else { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, response.message, 0, self.IS_DEBUG); - callback(response) - } - }) - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - Module : Get Device Information - Author : Mayank [SOFTWEB] - Inputs : msgType - Output : Devie info - Date : 2018-01-24 - */ - // getSyncData(messageType) { - // try { - // this.commonLib.getSyncData(this.CLIENT_CONNECTION, this.UNIQUE_ID, this.CPID, this.offlineFileConfig, messageType, function (response) { - // console.log("Requested for device details."); - // }) - // } catch (error) { - // console.log("Get device detail error :: ", error.message) - // // callback({ - // // status: false, - // // data: error, - // // message: error.message - // // }) - // } - // } - - /* - Module : Device Connection process - Author : Mayank [SOFTWEB] - Inputs : - Output : Request for the value which have data - Date : 2021-02-02 - */ - reqDataForActiveProperty(resData) { - var self = this; - try { - async.series([ - function(pcb){ - if(resData['d'] == 1){ - self.getSyncDataByCommandType(config.msgType.childDevice, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['attr'] == 1){ - self.getSyncDataByCommandType(config.msgType.attribute, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['set'] == 1){ - self.getSyncDataByCommandType(config.msgType.setting, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['r'] == 1){ - self.getSyncDataByCommandType(config.msgType.rule, function(res){ - pcb(); - }); - } else { - pcb(); - } - }, - function(pcb){ - if(resData['ota'] == 1){ - self.getSyncDataByCommandType(config.msgType.ota, function(res){ - pcb(); - }); - } else { - pcb(); - } - } - ], - function(err, results){ }); - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Device Connection process - Author : Mayank [SOFTWEB] - Inputs : - Output : Global callback for command and other data - Date : 2020-04-13 - */ - deviceConnectionProcess() { - var self = this; - try { - self.clientConnection(function (clientResponse) { - if (clientResponse.status) { - self.DEVICE_CONNECTED = true; - self.STOP_SDK_CONNECTION = true; - self.startCommandSubscriber(function(response){ - // console.log("=========== sub responseData ==> ", response); - if(response.status) { - var responseData = cache.get(self.SID + "_" + self.UNIQUE_ID); - // console.log("=========== sub responseData ==> ", responseData); - if(responseData && "has" in responseData) { - self.reqDataForActiveProperty(responseData.has); - } else { // For Azure - setTimeout(() => { - self.getSyncDataByCommandType(config.msgType.all, function(res){ - // console.log("all 200 request send => ",res); - }); - }, 1000); - } - } else { - self.commonLib.manageDebugLog("ERR_IN17", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - }); - } else { - self.commonLib.manageDebugLog("ERR_IN13", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - }) - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Client Connection - Author : Mayank [SOFTWEB] - Inputs : uniqueId, sdk Option params - Output : Connected brokr client object - Date : 2020-04-13 - */ - clientConnection(callback) { - var self = this; - try { - self.commonLib.clientConnection(function (response) { - callback({ - status: response.status, - data: response, - message: response.message - }) - }) - } catch (error) { - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - Module : Start Command subscriber - Author : Mayank [SOFTWEB] - Inputs : device client connection - Output : start listner - Date : 2018-01-24 - */ - startCommandSubscriber(callback) { - var self = this; - try { - self.commonLib.subscriberProcess(function (response) { - if (response.status) { - if(response.data.cmdReceiveType == "cmd"){ - if(!response.data.data.d) { - self.manageCommand(response.data); - } else { - self.manageDeviceInfo(response.data.data); - } - } - - if(response.data.cmdReceiveType == "twin"){ - if(self.TWIN_CHANGED_CALLBACK) - self.TWIN_CHANGED_CALLBACK(response.data.data); - } - } - }); - callback({ - status: true, - data: null, - message: "Devie subscription started." - }) - } catch (error) { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: error, - message: error.message - }) - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : uniqueId, message from subscribed listener - Output : Manage Command - Date : 2020-04-13 - */ - manageCommand(response) { - var self = this; - var cmdType = response.data.cmdType; - switch (response.data.cmdType) { - case config.commandType.CORE_COMMAND: //1 - Ok device - self.commonLib.manageDebugLog("INFO_CM01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var data = response.data.data; - if(self.DEVICE_CMD_CALLBACK) - self.DEVICE_CMD_CALLBACK(data); - break; - - case config.commandType.FIRMWARE_UPDATE: //2 - Firmware update - self.commonLib.manageDebugLog("INFO_CM02", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var data = response.data.data; - if(self.OTA_CMD_RECEIVED_CALLBACK) - self.OTA_CMD_RECEIVED_CALLBACK(data); - break; - - case config.commandType.ATTRIBUTE_INFO_UPDATE: //10 - Attribute Changed - self.commonLib.manageDebugLog("INFO_CM03", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.attributeParams; - break; - - case config.commandType.SETTING_INFO_UPDATE: //11 - Setting Changed - self.commonLib.manageDebugLog("INFO_CM04", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.settingsParams; - break; - - // case config.commandType.PASSWORD_INFO_UPDATE: //12 - Password Changed - // self.commonLib.manageDebugLog("INFO_CM05", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - // // var requestedParams = config.protocolParams; - // var requestedParams = undefined; - // // if (self.DEVICE_CONNECTED) { - // // // var deviceConnection = self.CLIENT_CONNECTION; - // // // deviceConnection.end(); - // // console.log("disconnect 1.0.0"); - // // self.disconnect(); - // // // self.DEVICE_CONNECTED = false; - // // // self.STOP_SDK_CONNECTION = false; - // // } - // break; - - case config.commandType.DEVICE_INFO_UPDATE: //13 - Device Changed - self.commonLib.manageDebugLog("INFO_CM06", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.deviceParams; - break; - - case config.commandType.RULE_INFO_UPDATE: //15 - Rule Changed - self.commonLib.manageDebugLog("INFO_CM07", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.ruleParams; - break; - - case config.commandType.STOP_SDK_CONNECTION: //99 - STOP SDK CONNECTION - self.commonLib.manageDebugLog("INFO_CM08", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - self.disconnect(config.commandType.STOP_SDK_CONNECTION); - var requestedParams = undefined; - break; - - case config.commandType.DEVICE_CONNECTION_STATUS: //16 - Connection status true/false - var data = response.data.data; - if(data.command) { - self.DEVICE_CONNECTED = true; - // self.STOP_SDK_CONNECTION = true; - } else { - self.DEVICE_CONNECTED = false; - // self.STOP_SDK_CONNECTION = false; - } - var requestedParams = undefined; - self.commonLib.manageDebugLog("INFO_CM09", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(self.CONNECTION_STATUS_CALLBACK) - self.CONNECTION_STATUS_CALLBACK(data); - break; - - case config.commandType.DATA_FREQUENCY_UPDATE: //17 - Data Frequency Updated - self.commonLib.manageDebugLog("INFO_CM18", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - var requestedParams = config.allStatusParams; - break; - - default: - break; - } - - if (requestedParams != "" && requestedParams != undefined) { - self.commonLib.syncDeviceOnDemand(requestedParams, cmdType, function (response) { - if (cmdType == config.commandType.PASSWORD_INFO_UPDATE) { - setTimeout(() => { - self.deviceConnectionProcess() - }, 3000); - } else { - self.startEdgeDeviceProcess(requestedParams); - } - }); - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : uniqueId, device data - Output : Manage Device information - Date : 2020-05-04 - */ - manageDeviceInfo(response) { - var self = this; - var ctStatus = response.d.ct; - var cacheId = self.SID+"_"+self.UNIQUE_ID; - // console.log("response.d => ", response.d); - switch (ctStatus) { - case config.msgType.allStatus: //200 - All data - // console.log("response.d ==> ", response.d) - if (response.d.ec == 0 && response.d.ct == config.msgType.allStatus) { - response.d["id"] = self.UNIQUE_ID; - response.d["sid"] = self.SID; - if(response.d.meta && response.d.meta.tg){ - response.d["d"] = [ { "tg": response.d.meta.tg, "id": self.UNIQUE_ID, "s": 0 } ] - self.SDK_OPTIONS.isGatewayDevice = true; - } else { - response.d["d"] = [ { "tg": '', "id": self.UNIQUE_ID, "s": 0 } ] - self.SDK_OPTIONS.isGatewayDevice = false; - } - // response.d["env"] = self.ENV; - // console.log("response.d ==> ", JSON.stringify(response.d)); - cache.put(cacheId, response.d); - // console.log("======= > ", cache.get(cacheId)); - this.reqDataForActiveProperty(response.d.has); - // self.startEdgeDeviceProcess(); - self.commonLib.manageDebugLog("INFO_CM11", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - case config.msgType.attribute: //201 - attribute - if (response.d.ec == 0 && response.d.ct == config.msgType.attribute) { - var deviceData = cache.get(cacheId); - deviceData["att"] = response.d['att']; - cache.put(cacheId, deviceData); - self.commonLib.manageDebugLog("INFO_CM12", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - self.ATTR_ACTIVE = true; - // console.log("attribute ",self.ATTR_ACTIVE + "=== "+ self.RULE_ACTIVE); - if(self.ATTR_ACTIVE && self.RULE_ACTIVE && (self.DEVICE_ACTIVE || deviceData.meta.tg == "") ){ - self.startEdgeDeviceProcess(); - } - - if(self.ATTR_ACTIVE && (self.DEVICE_ACTIVE || deviceData.meta.tg == "") ){ - if(self.ATTRIBUTE_CHANGED_CALLBACK){ - self.ATTRIBUTE_CHANGED_CALLBACK(response.d['att']); - } - } - } - break; - - case config.msgType.setting: //202 - setting - if (response.d.ec == 0 && response.d.ct == config.msgType.setting) { - var deviceData = cache.get(cacheId); - deviceData["set"] = response.d['set']; - cache.put(cacheId, deviceData); - self.commonLib.manageDebugLog("INFO_CM13", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } - break; - - case config.msgType.rule: //203 - rule - if (response.d.ec == 0 && response.d.ct == config.msgType.rule) { - var deviceData = cache.get(cacheId); - deviceData["r"] = response.d['r']; - cache.put(cacheId, deviceData); - self.RULE_ACTIVE = true; - self.commonLib.manageDebugLog("INFO_CM14", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(self.ATTR_ACTIVE && self.RULE_ACTIVE && self.DEVICE_ACTIVE){ - // console.log("rule ",self.ATTR_ACTIVE + "=== "+ self.RULE_ACTIVE); - self.startEdgeDeviceProcess(); - } - } - break; - - case config.msgType.childDevice: //204 - childDevice - if (response.d.ec == 0 && response.d.ct == config.msgType.childDevice) { - var deviceData = cache.get(cacheId); - deviceData["d"] = response.d['d']; - cache.put(cacheId, deviceData); - self.DEVICE_ACTIVE = true; - self.commonLib.manageDebugLog("INFO_CM15", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(self.ATTR_ACTIVE && self.RULE_ACTIVE && self.DEVICE_ACTIVE){ - // console.log("rule ",self.ATTR_ACTIVE + "=== "+ self.RULE_ACTIVE); - self.startEdgeDeviceProcess(); - } - // console.log("attribute changed from de vice => ",self.ATTR_ACTIVE + "=== "+ self.RULE_ACTIVE); - if(self.ATTR_ACTIVE && (self.DEVICE_ACTIVE || deviceData.meta.tg == "") ){ - if(self.ATTRIBUTE_CHANGED_CALLBACK){ - self.ATTRIBUTE_CHANGED_CALLBACK(response.d['att']); - } - } - } - break; - - case config.msgType.ota: //205 - ota - if (response.d.ec == 0 && response.d.ct == config.msgType.ota) { - var deviceData = cache.get(cacheId); - deviceData["ota"] = response.d['ota']; - cache.put(cacheId, deviceData); - // if(self.OTA_CMD_RECEIVED_CALLBACK){ - // self.OTA_CMD_RECEIVED_CALLBACK(response.d['ota']); - // } - } - break; - - case config.msgType.all: //210 - All information - if (response.d.ec == 0 && response.d.ct == config.msgType.all) { - var deviceData = {}; - response.d["id"] = self.UNIQUE_ID; - response.d["sid"] = self.SID; - cache.put(cacheId, response.d); - self.ATTR_ACTIVE = true; - self.RULE_ACTIVE = true; - self.DEVICE_ACTIVE = true; - self.commonLib.manageDebugLog("INFO_CM17", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - if(self.ATTR_ACTIVE && self.RULE_ACTIVE && self.DEVICE_ACTIVE){ - self.startEdgeDeviceProcess(); - } - if(self.ATTR_ACTIVE && self.DEVICE_ACTIVE ){ - if(self.ATTRIBUTE_CHANGED_CALLBACK){ - self.ATTRIBUTE_CHANGED_CALLBACK(response.d["att"]); - } - } - } - break; - - default: - // console.log(cpid + "_" + uniqueId + " :: SYNC MessageType :: " + ctStatus + " :: UNKNOWN_COMMAND_FOUND"); - break; - } - } - - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : - Output : Edge devie processing - Date : 2020-04-14 - */ - startEdgeDeviceProcess(requestedParams = "") { - var self = this; - var responseData = cache.get(self.SID + "_" + self.UNIQUE_ID); - if (responseData.meta.edge == config.edgeEnableStatus.enabled) { - async.series([ - function (cb_series) { - try { - self.commonLib.setEdgeConfiguration(responseData.att, responseData.d, function (res) { - if (res.status) { - responseData.edgeData = res.data.mainObj; - if ((requestedParams && requestedParams.attribute) || requestedParams == "") { - async.forEachSeries(res.data.intObj, function (data, cb_inner) { - self.commonLib.setIntervalForEdgeDevice(data.tumblingWindowTime, data.lastChar, data.edgeAttributeKey, data.uniqueId, data.attrTag, data.devices); - cb_inner(); - }, function () {}); - } - } - cb_series(); - }); - } catch (err) { - cb_series(); - } - }, - function (cb_series) { - try { - // console.log("responseData.r ==> ", responseData.r); - setTimeout(() => { - self.commonLib.setRuleaConfiguration(responseData.r, self.UNIQUE_ID, function (res) { - if (res.status) { - responseData.rulesData = res.data; - } else { - self.commonLib.manageDebugLog("ERR_IN01", self.UNIQUE_ID, self.SID, res.message, 0, self.IS_DEBUG); - } - cb_series(); - }); - }, 500); - } catch (err) { - cb_series(); - } - } - ], function (err, response) { }) - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : uniqueId (Device serial number) - Output : Device detail with all atrributes - Date : 2018-01-24 - */ - sendData(data) { - var self = this; - if (data != "" && data.length > 0 && typeof data == 'object') { - try { - // var dateTimeArray = data.filter(date => { - // if (self.checkDateObjFormat(date.time)) { - // return true; - // } else { - // return true; - // } - // }); - //dateTimeArray.length == data.length - if (self.STOP_SDK_CONNECTION && self.UNIQUE_ID == data[0].uniqueId) { - self.commonLib.SendDataToHub(data, function (response) { - if (response.status) {} - }) - } else { - if (self.UNIQUE_ID != data[0].uniqueId) { - self.commonLib.manageDebugLog("ERR_SD02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - // if (dateTimeArray.length != data.length) { - // self.commonLib.manageDebugLog("ERR_SD03", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - // } - if (self.STOP_SDK_CONNECTION == false) { - self.commonLib.manageDebugLog("ERR_SD04", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } catch (err) { - console.log(" err => ", err); - self.commonLib.manageDebugLog("ERR_SD01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } else { - if (!data) { - self.commonLib.manageDebugLog("ERR_SD06", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - if (typeof data != 'object') { - self.commonLib.manageDebugLog("ERR_SD05", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : - Output : Device detail with all atrributes - Date : 2018-04-06 - */ - getAttributes(callback) { - var self = this; - try { - // var deviceUniqueId = self.UNIQUE_ID; - self.commonLib.getAttributes(function (response) { - if (response.status) { - var sdkDataArray = []; - async.forEachSeries(response.data.device, function (device, callbackdev) { - var attArray = { - "device": { - "id": device.id, - "tg": device.tg == "" ? undefined : device.tg - }, - "attributes": [] - } - var attributeData = response.data.attribute; - async.forEachSeries(attributeData, function (attrib, callbackatt) { - if (attrib.p == "") // Parent - { - if (attrib.dt == 2) { - console.log(attrib) - if (attrib.p != "") { - delete attrib.agt; - var pcAttributes = { - "ln": attrib.p, - "dt": self.dataTypeToString(attrib.dt), - "tw": attrib.tw == "" ? undefined : attrib.tw, - "d": [] - }; - } - async.forEachSeries(attrib.d, function (att, cb_attr) { - if (att.tg == device.tg) // Parent - { - var cAttribute = { - "ln": att.ln, - "dt": self.dataTypeToString(att.dt), - "dv": att.dv, - "tg": att.tg == "" ? undefined : att.tg, - "tw": att.tw == "" ? undefined : att.tw - } - pcAttributes.d.push(cAttribute) - } - cb_attr(); - }, function () { - console.log(pcAttributes); - attArray['attributes'].push(pcAttributes) - callbackatt(); - }) - } else { - async.forEachSeries(attrib.d, function (att, cb_attr) { - if (att.tg == device.tg) // Parent - { - if (att.tg == "") - delete att.tg; - delete att.agt; - att.dt = self.dataTypeToString(att.dt) - attArray['attributes'].push(att); - } - cb_attr(); - }, function () { - callbackatt(); - }) - } - } else { - if (attrib.tg == device.tg) // Parent - { - if (attrib.p != "") { - delete attrib.agt; - var pcAttributes = { - "ln": attrib.p, - "dt": self.dataTypeToString(attrib.dt), - "tg": attrib.tg == "" ? undefined : attrib.tg, - "tw": attrib.tw == "" ? undefined : attrib.tw, - "d": [] - }; - } - async.forEachSeries(attrib.d, function (att, cb_attr) { - if (att.tg == device.tg) // Parent - { - var cAttribute = { - "ln": att.ln, - "dt": self.dataTypeToString(att.dt), - "dv": att.dv, - "tg": att.tg == "" ? undefined : att.tg, - "tw": att.tw == "" ? undefined : att.tw - } - pcAttributes.d.push(cAttribute) - } - cb_attr(); - }, function () { - attArray['attributes'].push(pcAttributes) - callbackatt(); - }) - } else { - callbackatt(); - } - } - }, function () { - sdkDataArray.push(attArray); - callbackdev(); - }) - }, function () { - self.commonLib.manageDebugLog("INFO_GA01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - callback({ - status: true, - data: sdkDataArray, - message: "Attribute get successfully." - }); - }) - } else { - self.commonLib.manageDebugLog("ERR_GA02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - callback({ - status: false, - data: null, - message: "Attributes data not found" - }); - } - }) - } catch (err) { - self.commonLib.manageDebugLog("ERR_GA01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - callback({ - status: false, - data: err, - message: err.message - }); - } - } - - /* - Module : Device - Author : Mayank [SOFTWEB] - Inputs : Key, Value - Output : Device list - Date : 2019-06-11 - */ - updateTwin(key, value) { - var self = this; - try { - if (self.STOP_SDK_CONNECTION == true && key && (value || value === null)) { - var obj = {}; - obj[key] = value; - self.commonLib.UpdateTwin(obj, function (response) { - if (response.status) { - self.commonLib.manageDebugLog("INFO_TP01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } else { - self.commonLib.manageDebugLog("ERR_TP01", self.UNIQUE_ID, self.SID, response.message, 0, self.IS_DEBUG); - } - }) - } else { - if (self.STOP_SDK_CONNECTION == false) { - self.commonLib.manageDebugLog("ERR_TP02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - if (!key || !value) { - self.commonLib.manageDebugLog("ERR_TP03", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } catch (err) { - self.commonLib.manageDebugLog("ERR_TP01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } - - - /* - Module : Device disconnect - Author : Mayank [SOFTWEB] - Inputs : uniqueID, client connecction - Output : device disconnected message - Date : 2019-06-11 - */ - disconnect(hardStopCmd = "") { - var self = this; - try { - console.log("self.DEVICE_CONNECTED => ", self.DEVICE_CONNECTED); - if (self.DEVICE_CONNECTED) { - self.commonLib.disconnectDevice(function (response) { - if(response.status){ - self.DEVICE_CONNECTED = false; - if(hardStopCmd){ - self.STOP_SDK_CONNECTION = false; - self.commonLib.deleteAllLogFile(self.LOG_PATH); - } - } - }) - } else { - if (self.DEVICE_CONNECTED == false) { - self.commonLib.manageDebugLog("INFO_DC01", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - } else { - self.commonLib.manageDebugLog("ERR_DC02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_DC01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : Send command ack - Author : Mayank [SOFTWEB] - Inputs : data, time and message type - Output : message - Date : 2020-03-11 - */ - sendAck(objdata, mt) { - var self = this; - try { - if (this.STOP_SDK_CONNECTION == true && objdata && typeof objdata == 'object' && mt) { - self.commonLib.sendCommandAck(objdata, mt, function (response) { - self.commonLib.manageDebugLog("INFO_CM10", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - }) - } else { - if (self.STOP_SDK_CONNECTION == false) { - self.commonLib.manageDebugLog("ERR_CM04", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - if (!objdata || !mt) { - self.commonLib.manageDebugLog("ERR_CM02", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } else { - if (typeof objdata != "object") { - self.commonLib.manageDebugLog("ERR_CM03", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_CM01", self.UNIQUE_ID, self.SID, error.message, 0, self.IS_DEBUG); - } - } - - /* - Module : get all twins properties - Author : Mayank [SOFTWEB] - Inputs : - Output : publish message - Date : 2020-04-20 - */ - getAllTwins() { - var self = this; - try { - if (this.STOP_SDK_CONNECTION == true && self.DEVICE_CONNECTED == true ) { - self.commonLib.getAllTwins(function (response) { - self.commonLib.manageDebugLog("INFO_TP02", self.UNIQUE_ID, self.SID, "", 1, self.IS_DEBUG); - }) - } else { - self.commonLib.manageDebugLog("ERR_TP04", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } catch (error) { - self.commonLib.manageDebugLog("ERR_TP01", self.UNIQUE_ID, self.SID, err.message, 0, self.IS_DEBUG); - } - } - - async checkDateObjFormat(dateObj) { - if (Object.prototype.toString.call(dateObj) === "[object Date]") { - if (isNaN(dateObj.getTime())) { - return false; - } else { - return true; - } - } else { - return false; - } - } - - async dataTypeToString(value) { - switch (value) { - case config.dataType.number: // 0 = number - return 'number'; - case config.dataType.string: // 1 = string - return 'string' - case config.dataType.object: // 2 = object - return 'object'; - } - } - - async setConnectionStatusChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.CONNECTION_STATUS_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM05", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setTwinChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.TWIN_CHANGED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM06", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setDeviceCommandCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.DEVICE_CMD_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM07", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - - } - } - - async setOTAReceivedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.OTA_CMD_RECEIVED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM08", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setAttributeChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.ATTRIBUTE_CHANGED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM09", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setDeviceChangedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.DEVICE_CHANGED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM10", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async setModuleReceivedCallback(callback) { - var self = this; - if(typeof callback == "function"){ - self.MODULE_RECEIVED_CALLBACK = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM11", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } - - async getSecrets(callback) { - var self = this; - if(typeof callback == "function"){ - self.REQUEST_FOR_SECRET_CONFIGURATION = callback; - } else { - self.commonLib.manageDebugLog("ERR_CM11", self.UNIQUE_ID, self.SID, "", 0, self.IS_DEBUG); - } - } -} - -module.exports = Tpm; \ No newline at end of file diff --git a/package.json b/package.json index c036c50..062e4d1 100644 --- a/package.json +++ b/package.json @@ -14,19 +14,15 @@ "private": true, "dependencies": { "async": "^2.0.0", - "azure-iot-device": "^1.17.3", - "azure-iot-device-mqtt": "^1.15.3", - "azure-iot-provisioning-device": "^1.8.7", - "azure-iot-provisioning-device-http": "^1.8.7", - "azure-iot-provisioning-service": "^1.8.7", - "azure-iot-security-tpm": "^1.8.7", "bluebird": "^3.7.1", "fs-extra": "^7.0.1", "fs-extra-promise": "^1.0.1", "iotconnect-sdk": "file:iotconnect-sdk", + "is-online": "9.0.1", "json-query": "^2.2.2", "memory-cache": "^0.2.0", - "mqtt": "^1.12.0", + "moment": "^2.29.4", + "mqtt": "^5.1.3", "request": "^2.85.0", "url": "^0.11.0" } diff --git a/sample/az/example.js b/sample/az/example.js deleted file mode 100644 index 501aec3..0000000 --- a/sample/az/example.js +++ /dev/null @@ -1,441 +0,0 @@ -'use strict'; - -var SDKClient = require('iotconnect-sdk'); -var iotConnectSDK = ""; - -// console.log(SDKClient); -// return false; -var readline = require('readline'); -var async = require('async'); -var fs = require('fs-extra'); -// const { try } = require('bluebird'); -var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); -var env = process.argv[2]; -var sdkOptions = { - "debug" : true, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimted - "fileCount": 5 // Default value = 1 - } -} -var isDeviceConnected = false; - -var dc = "<>"; -var sIdd = "<>"; - -async.series([ - function(cb_series) { - rl.question('Enter device connection sting : ', function (deviceConnectionString) { - deviceConnectionString = dc; - rl.question('Enter SID : ', function (sId) { - sId = sIdd; - if(sdkOptions.certificate){ - try { - var CERT_PATH_FLAG = true; - async.forEachSeries(Object.values(sdkOptions.certificate), function (filePath, cb_inner) { - if(!fs.existsSync(filePath)) { - CERT_PATH_FLAG = false; - } - cb_inner(); - }, function () { - if(CERT_PATH_FLAG == true) { - try { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(deviceConnectionString, sId, deviceCallback, twinUpdateCallback, sdkOptions, env); - } else { - console.log("Device is already connected"); - } - } catch (error) { - console.log("Error : ", error.message ) - } - cb_series(); - } else { - console.log("Set proper certificate file path and try again.") - process.exit(); - } - }); - } catch (error) { - console.log("Error : ", error.message); - } - } else { - if(!isDeviceConnected) { - // iotConnectSDK = new SDKClient(cpId, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); - iotConnectSDK = new SDKClient(deviceConnectionString, sId, sdkOptions, function(response){ - // console.log("Sdk callback => ", response); - if(response.status){ - // iotConnectSDK.connect(); - setTimeout(() => { - // console.log("==================================== connect ") - iotConnectSDK.connect(); - initCallbacks(); - }, 5000); - } else { - console.log("DeviceId :: SDK initialization failed :: ", new Date()); - } - }); - } else { - console.log("Device is already connected"); - } - cb_series(); - } - }); - }); - } -], function(err, response) { }) - -var getAttributest = function getAttributest(){ - iotConnectSDK.getAttributes(function(response){ - try { - // console.log("response.data ==>", JSON.stringify(response.data)); - SendData(response.data); - } catch (error) { - console.log("Error while getting attributes :: ",error); - } - }) -} - -var deviceCallback = function deviceCallback(data){ - - if(data != null && data != undefined && data.ack != undefined && data.cmdType != null) - { - if(data.ct == 0) { - // console.log("\n"+"--- Device Command Received ---"); - // console.log(data); - var msgType = 5; - var obj = { - "ack": data.ack, - "type": 0, - "st": 6, - "msg": "Success", - "cid": data.id ? data.id : null - } - if(data.ack != null) - iotConnectSDK.sendAck(obj, msgType) - } - - // if(data.cmdType == '0x01') { - // console.log("\n"+"--- Device Command Received ---"); - // console.log(data); - // var obj = { - // "ackId": data.ackId, - // "st": 6, - // "msg": "", - // "childId": "" - // } - // var msgType = 5; - // if(data.ackId != null) - // iotConnectSDK.sendAck(obj, msgType) - // } else if(data.cmdType == '0x02') { - // console.log("\n"+"--- OTA Command Received ---"); - // console.log(data); - // if(data.urls) { - // async.forEachSeries(data.urls, function (cmddetail, cbota) { - // if("uniqueId" in cmddetail) { - // var childId = cmddetail.uniqueId; - // } else { - // var childId = null; - // } - // var obj = { - // "ackId": data.ackId, - // "st": 7, - // "msg": "", - // "childId": childId - // } - // var msgType = 11; - // if(data.ackId != null) - // { - // /* - // Type : Public Method "sendAck()" - // Usage : Send firmware command received acknowledgement to cloud - // - status Type - // st = 7; // firmware - // - Message Type - // msgType = 11; // for "0x02" Firmware command - // */ - // console.log("obj => ", obj); - // iotConnectSDK.sendAck(obj, msgType) - // } - // cbota(); - // }, function () { }); - // } - // } else if(data.cmdType == '0x16') { - // // console.log("\n"+"--- Device connection status ---"); - // // console.log(data); - // // try{ - - // // iotConnectSDK.getAllTwins(); - // // } catch(e) { - // // console.log(e) - // // } - // // setTimeout(() => { - // // // getAttributest(); - // // console.log("hello get all twins"); - // // }, 10000); - // try { - // if(data.command) - // { - // isDeviceConnected = true; - - // console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - // } else { - // isDeviceConnected = false; - // console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - // } - // } catch (error) { - // console.log("Error while getting attributes :: ",error.message); - // } - // } - } -} - -var twinUpdateCallback = function twinUpdateCallback(data){ - console.log("\n"+"--- Twin desired message received ---"); - console.log(data); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (key, callbackatt) { - if(key == "$version"){ - callbackatt(); - } else { - var value = data.desired[key]; - iotConnectSDK.updateTwin(key, value) - callbackatt(); - } - }, function () { }) - } -} - -var setReadline = function setReadline (attr, type, callback){ - if(type == 1) - var space = " "; - else - var space = ""; - rl.question(space+'Enter '+attr+' : ', function (value) { - var obj = {}; - obj[attr] = value; - callback(obj); - }); -} - -var callAgain = function callAgain (){ - rl.question('\nWould you like to send data again ? (Y/N) : ', function (status) { - if(status == "Y" || status == "y") - { - try { - getAttributest(); - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } - else - process.exit(); - }); -} - -var SendData = function SendData(sensordata){ - var sendTeledataData = []; - var cnt = 0; - var text = ""; - var tagArray = []; - if(sensordata.length > 0) { - async.forEachSeries(sensordata, function(inputdata, data_cb) { - if(cnt == 0 && inputdata.device.tg) { - console.log("Note :: It includes the single device from each tag."); - text = "(Gateway Device) "; - } else { - text = ""; - } - if(inputdata['attributes'].length > 0) - { - cnt++; - if (tagArray.indexOf(inputdata.device.tg) == -1) { - // tagArray.push(inputdata.device.tg); - if(inputdata.device.tg) - console.log("\n## TAG :: "+inputdata.device.tg+" [Device "+text+":: "+inputdata.device.id+"]"); - else - console.log("\n## Device "+text+":: "+inputdata.device.id); - var sendordataObj = { - "uniqueId": inputdata.device.id, - "time" : new Date(), - "data": {} - } - async.forEachSeries(inputdata.attributes, function(attr, attrdata_cb) { - if(attr.d) - { - console.log("Enter "+attr.ln+" : "); - sendordataObj.data[attr.ln] = {}; - async.forEachSeries(attr.d, function(attrChild, attrdataChild_cb) { - setReadline(attr.ln+'.'+attrChild.ln, 1, function(resultdata){ - sendordataObj.data[attr.ln][attrChild.ln] = resultdata[attr.ln+'.'+attrChild.ln]; - attrdataChild_cb() - }); - },function(){ - attrdata_cb() - }); - } - else - { - setReadline(attr.ln, 0, function(resultdata){ - sendordataObj.data[attr.ln] = resultdata[attr.ln]; - attrdata_cb(); - }); - } - },function(){ - sendTeledataData.push(sendordataObj); - data_cb(); - }); - } else { - data_cb(); - } - } - },function(){ - var data = sendTeledataData; - iotConnectSDK.sendData(data); - setTimeout(function() { - callAgain(); - }, 500); - }); - } else { - console.log("No Attribute data found."); - } -} - -function disconnectDevice(){ - if(isDeviceConnected) { - iotConnectSDK.disconnect(); - } else { - console.log("Device is already disconnected"); - } -} - - -// Callback function for the connection status -var connectionStatusChanged = function connectionStatusChanged(data){ - if(data.ct == 3) { - console.log("\n"+"--- Device connection status ---"); - console.log(data); - try { - if(data.command) - { - isDeviceConnected = true; - setTimeout(() => { - //getAttributest(); - // iotConnectSDK.getAllTwins(); - }, 20000); - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - } - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } else { - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Wrong command :: ", new Date()); - } -} - -// Callback function for the Attribute updated -var attributeUpdated = function attributeUpdated(data){ - // console.log("--- Attribute information updated ---", data); - if(data) - getAttributest(); -} - -// Callback function for the device updated -var deviceUpdated = function deviceUpdated(data){ - console.log("Device Updated => ", data); -} - -// Callback function to receive OTA command -var receiveOTA = function receiveOTA(data){ - console.log("Receive OTA => ", JSON.stringify(data)); - if(data && data.ct == 1) { - var obj = { - "ack": data.ack, - "type": data.ct, - "st": 7, - "msg": "Success", - "cid": "" // For gatewat device only for child device - } - var msgType = 6; - if(data.ack != null) - { - iotConnectSDK.sendAck(obj, msgType) - } - } else { - console.log("Wrong command ") - } - // if(data.ct == '0x02') { - // console.log("\n"+"--- OTA Command Received ---"); - // // console.log(data); - // if(data.urls) { - // async.forEachSeries(data.urls, function (cmddetail, cbota) { - // if("uniqueId" in cmddetail) { - // var childId = cmddetail.uniqueId; - // } else { - // var childId = null; - // } - // var obj = { - // "ackId": data.ackId, - // "st": 7, - // "msg": "", - // "childId": childId - // } - // var msgType = 11; - // if(data.ackId != null) - // { - // /* - // Type : Public Method "sendAck()" - // Usage : Send firmware command received acknowledgement to cloud - // - status Type - // st = 7; // firmware - // - Message Type - // msgType = 11; // for "0x02" Firmware command - // */ - // iotConnectSDK.sendAck(obj, msgType) - // } - // cbota(); - // }, function () { }); - // } - // } -} - -// Callback function to receive the module information -var moduleReceived = function moduleReceived(data){ - console.log("module received => ", data); - if(data && data.ct == 2) { - var obj = { - "ack": data.ack, - "type": data.ct, - "st": 0, - "msg": "Success", - "cid": "" // For gatewat device only for child device - } - var msgType = 6; - if(data.ack != null) - { - iotConnectSDK.sendAck(obj, msgType) - } - } else { - console.log("Wrong command ") - } -} - -var initCallbacks = function initCallbacks(){ - // console.log("iotConnectSDK => ", iotConnectSDK); - iotConnectSDK.setConnectionStatusChangedCallback(connectionStatusChanged) - iotConnectSDK.setTwinChangedCallback(twinUpdateCallback) - iotConnectSDK.setDeviceCommandCallback(deviceCallback) - iotConnectSDK.setOTAReceivedCallback(receiveOTA) - iotConnectSDK.setAttributeChangedCallback(attributeUpdated) - iotConnectSDK.setDeviceChangedCallback(deviceUpdated) - iotConnectSDK.setModuleReceivedCallback(moduleReceived) -} - -// setTimeout(() => { -// disconnectDevice(); -// }, 30000); \ No newline at end of file diff --git a/sample/az/firmware.js b/sample/az/firmware.js deleted file mode 100644 index 07f20a7..0000000 --- a/sample/az/firmware.js +++ /dev/null @@ -1,259 +0,0 @@ -'use strict'; - -/* -Hope you have installed the node SDK as guided on SDK documentation. -*/ -var SDKClient = require('iotconnect-sdk'); -var async = require('async'); - -/* -## Prerequisite parameter to run this sampel code -- cpId :: It need to get from the IoTConnect platform "Settings->Key Vault". -- uniqueId :: Its device ID which register on IotConnect platform and also its status has Active and Acquired -- env :: It need to get from the IoTConnect platform "Settings->Key Vault". -- dataSendInterval :: send data frequency in seconds -- disconnectDuration:: Device connection close after defined time in seconds to call dispose() method. Keep "0" if don't need disconnect the device. -- sdkOptions :: It helps to define the path of self signed and CA signed certificate as well as define the offlinne storagr params -*/ -var cpId = "<< CPID >>"; -var uniqueId = "<< Device UniqueID >>"; -var env = "<< Environment >>"; //Environment DEV, QA, POC, AVNET, PROD - (Default - PROD) -var dataSendInterval = 10; // send data frequency in seconds -var disconnectDuration = 0; //Seconds // Keep "0" If no need to disconnect -var isDeviceConnected = false; - -/* -Note: sdkOptions is optional. Mandatory for "certificate" X.509 device authentication type and discoveryUrl. - "certificate": //For SSL CA signed and SelfSigned authorized device only otherwise skip this property - - SSLKeyPath: your device key - - SSLCertPath: your device certificate - - SSLCaPath : Root CA certificate - "offlineStorage": It helps, store the data in log file which will be created beside the firmware sample file. So, make sure your root directory has proper permission to create the log files and folder. It will store offline data once device lost the network connection. - - disabled : false = offline data storing, true = not storing offline data (Default = false) - - availSpaceInMb : Define the file size of offline data which should be in (MB) (Default = unlimited) - - fileCount : Number of file need to create for offline data (Default = 1) - - Note : It will create 5 files of 2 MB. - Define setting or leave it blank. It will set the default setting for offline storage configuration as per defined below. It may harm your device by storing the large data. Once memory get full may chance to your device script crash and stop the execution. -*/ - -var sdkOptions = { - "certificate": { - "SSLKeyPath" : "<< Certificate file path >>", - "SSLCertPath" : "<< Certificate file path >>", - "SSLCaPath" : "<< Certificate file path >>" - }, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimted - "fileCount": 5 // Default value = 1 - } -} - -/* -Type : Object Initialization "new SDKClient()" -Usage : To Initialize SDK and Device cinnection -Output : Callback methods for command and twin properties -Input : cpId, uniqueId, sdkOptions, env as explained above and deviceCallback and twinUpdateCallback is callback functions -*/ -var iotConnectSDK = ""; -setTimeout(() => { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(cpId, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); - } else { - console.log("Device is already connected"); - } -}, 1000); - - -/* -Type : Callback Function "deviceCallback()" -Usage : Firmware will receive commands from cloud. You can manage your business logic as per received command. -Output : Receive device command, firmware command and other device initialize error response -Input : -*/ -var deviceCallback = function deviceCallback(data){ - if(data != null && data != undefined && data.ack != undefined && data.cmdType != null) - { - if(data.cmdType == '0x01') { - console.log("\n"+"--- Device Command Received ---"); - console.log(data); - var obj = { - "ackId": data.ackId, - "st": 6, - "msg": "", - "childId": "" - } - var msgType = 5; - if(data.ackId != null) - { - /* - Type : Public Method "sendAck()" - Usage : Send device command received acknowledgment to cloud - - status Type - st = 6; // Device command Ack status OR - st = 4; // Failed Ack - - Message Type - msgType = 5; // for "0x01" device command - */ - if(iotConnectSDK) - { - iotConnectSDK.sendAck(obj, msgType) - } else { - console.log("Connection object not founud") - } - } - } else if(data.cmdType == '0x02') { - console.log("\n"+"--- Firmware OTA Command Received ---"); - console.log(data); - async.forEachSeries(data.urls, function (cmddetail, cbota) { - if("uniqueId" in cmddetail) { - var childId = cmddetail.uniqueId; - } else { - var childId = null; - } - var obj = { - "ackId": data.ackId, - "st": 7, - "msg": "", - "childId": childId - } - var msgType = 11; - if(data.ackId != null) - { - /* - Type : Public Method "sendAck()" - Usage : Send firmware command received acknowledgement to cloud - - status Type - st = 7; // firmware OTA command Ack status OR - st = 4; // Failed Ack - - Message Type - msgType = 11; // for "0x02" Firmware command - */ - if(iotConnectSDK) - { - iotConnectSDK.sendAck(obj, msgType) - } else { - console.log("Connection object not founud") - } - } - cbota(); - }, function () { }); - } else if(data.cmdType == '0x16') { - console.log("\n"+"--- Device connection status ---"); - console.log(data); - try { - if(data.command) - { - isDeviceConnected = true; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - } - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } - } -} - -/* -Type : Public Method "getAllTwins()" -Usage : To get all the twin properies Desired and Reported -Output : All twin property will receive in above callback function "twinUpdateCallback()" -*/ -// iotConnectSDK.getAllTwins(); - - -/* -Type : Callback Function "twinUpdateCallback()" -Usage : Manage twin properties as per business logic to update the twin reported property -Output : Receive twin properties Desired, Reported -Input : -*/ -var twinUpdateCallback = function twinUpdateCallback(data){ - // console.log("\n--- Twin desired message received ---"); - // console.log(data); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (key, callbackatt) { - if(key == "$version"){ - callbackatt(); - } else { - var value = data.desired[key]; - if(iotConnectSDK) - { - iotConnectSDK.updateTwin(key,value) - } else { - console.log("Connection object not founud") - } - callbackatt(); - } - }, function () { }) - } -} - -/* -Type : Public Method "updateTwin()" -Usage : Upate the twin reported property -Output : -Input : "key" and "value" as below - // var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message - // var value = "<< Desired Property value >>"; // Value of respective desired property -*/ -//iotConnectSDK.updateTwin(key,value) - - -/* -Type : Public Method "sendData()" -Usage : To publish the D2C data -Output : -Input : Predefined data object -*/ -setInterval(() => { - // Non Gateway - var data = [{ - "uniqueId":uniqueId, - "time":new Date(), - "data": {} // Add your device attributes and respective value here as per standard format defined in sdk documentation - }] - - // Gateway Device - // var data = [{ - // "uniqueId":uniqueId, - // "time":new Date(), - // "data": {} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // },{ - // "uniqueId":uniqueId, - // "time":new Date(), - // "data": {} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // },] - - if(iotConnectSDK) - { - // Device to Cloud data publish - iotConnectSDK.sendData(data) - } else { - console.log("Connection object not founud") - } -}, eval(dataSendInterval * 1000)); - - -/* -Type : Public Method "dispose()" -Usage : Disconnect the device from cloud -Output : -Input : -Note : It will disconnect the device after defined time -*/ -if(disconnectDuration && disconnectDuration > 0) { - setTimeout(() => { - if(iotConnectSDK && isDeviceConnected == true) - { - iotConnectSDK.dispose() - isDeviceConnected = false; - } else { - console.log("Connection object not founud") - } - }, eval(disconnectDuration * 1000)); -} \ No newline at end of file diff --git a/sample/example.js b/sample/example.js new file mode 100644 index 0000000..ce3c32a --- /dev/null +++ b/sample/example.js @@ -0,0 +1,416 @@ +"use strict"; + +var SDKClient = require("iotconnect-sdk"); +var iotConnectSDK = ""; +var readline = require("readline"); +var async = require("async"); +var fs = require("fs-extra"); +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +var cpId = "<>"; +var env = "<>"; +var pf = "<>"; + +var sdkOptions = { + certificate: { + // Self signed or CA signed device only + SSLCertPath: "", //"<>/device.pem", + SSLKeyPath: "", //"<>/device.key", + SSLCaPath: "", //"<>/rootCa.pem" + }, + offlineStorage: { + disabled: false, //default value = false, false = store data, true = not store data + availSpaceInMb: 1, //in MB Default value = unlimited + fileCount: 5, // Default value = 1 + }, + debug: false, // Private setting, false(default) = Don't show log, true = Show log + //"discoveryUrl": "", // Private setting, Default = "https://discovery.iotconnect.io" + skipValidation: false, // false(default) = Do validation, true = skip validation + keepalive: "", // Integer value only + cpId: cpId, + env: env, + pf: pf, +}; +var isDeviceConnected = false; + +var deviceId = ""; + +async.series( + [ + function (cb_series) { + rl.question("Enter device serial number : ", function (uniqueId) { + deviceId = uniqueId; + rl.question("Enter SID : ", function (sId) { + if (sdkOptions.certificate) { + try { + var CERT_PATH_FLAG = true; + async.forEachSeries( + Object.values(sdkOptions.certificate), + function (filePath, cb_inner) { + if (!fs.existsSync(filePath)) { + CERT_PATH_FLAG = false; + } + cb_inner(); + }, + function () { + if (CERT_PATH_FLAG == true) { + if (!isDeviceConnected) { + iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, initCallback); + } else { + console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Device is already connected :: ", new Date()); + } + cb_series(); + } else { + console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Set proper certificate file path and try again :: ", new Date()); + process.exit(); + } + } + ); + } catch (error) { + console.log("DeviceId ::: [" + uniqueId + "] :: Init :: error :: ", error.message, " :: ", new Date()); + } + } else { + if (!isDeviceConnected) { + iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, initCallback); + } else { + console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Device is already connected :: ", new Date()); + } + cb_series(); + } + }); + }); + }, + ], + function (err, response) {} +); + +var initCallback = function initCallback(response) { + if (response.status) { + startConnection(); + initCallbacks(); + console.log("DeviceId ::: [" + deviceId + "] :: SDK initialization Success :: ", new Date()); + } else { + console.log("DeviceId ::: [" + deviceId + "] :: SDK initialization failed ::", response.message, " :: ", new Date()); + } +}; + +var startConnection = function startConnection() { + iotConnectSDK.connect(successCallback, failedCallback, connectionStatusCallback); +}; + +// success callback +var successCallback = function successCallback(responseMessage) { + isDeviceConnected = true; + console.log("\nDeviceId ::: [" + deviceId + "] :: Connection success :: " + responseMessage + " :: ", new Date()); +}; + +// Failed callback +var failedCallback = function failedCallback(responseMessage) { + isDeviceConnected = false; + console.log("\nDeviceId ::: [" + deviceId + "] :: Connection failed :: " + responseMessage + " :: ", new Date()); +}; + +// Callback function for the connection status +var connectionStatusCallback = function connectionStatusCallback(response) { + if (response.command) { + isDeviceConnected = true; + setTimeout(() => { + getAttributes(); + // getChildDevices(); + // createChildDevice(); + // deleteChildDevice(); + // getTwins(); + }, 10000); + console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Connected :: ", new Date()); + } else { + isDeviceConnected = false; + console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Disconnected :: ", new Date()); + } +}; + +var childGlobal = []; +var getAttributes = function getAttributes() { + iotConnectSDK.getAttributes(function (response) { + try { + console.log("\nDeviceId ::: [" + deviceId + "] :: Get Attributes :: ", new Date()); + console.log("\nDeviceId ::: [" + deviceId + "] :: Attributes received :: ", JSON.stringify(response)); + + if (response.data && response.data instanceof Array && response.data.length) { + childGlobal = response.data.map((e) => e.device.id); + } + SendData(response.data); + } catch (error) { + console.log("Error while getting attributes :: ", error); + } + }); +}; + +var getChildDevices = function getChildDevices() { + iotConnectSDK.getChildDevices(function (response) { + try { + if (response.status) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices received :: ", new Date()); + console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices :: ", JSON.stringify(response)); + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices receive request failed :: ", response.message, " :: ", new Date()); + } + } catch (error) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices receive request failed :: ", error.message, " :: ", new Date()); + } + }); +}; + +var deviceCommandCBFunc = function deviceCommandCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Device Command :: ", new Date()); + console.log("\nDeviceId ::: [" + deviceId + "] :: Device command :: ", JSON.stringify(data)); + if (data && data.ct == 0 && data.ack) { + var ackGuid = data.ack; + var status = 7; // Failed = 4, Executed = 5, Success = 7 + var msg = "Success"; + var childId = data.id ? data.id : null; + iotConnectSDK.sendAckCmd(ackGuid, status, msg, childId); + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Device Command :: No ack :: ", JSON.stringify(data)); + } +}; + +var twinChangeCommandCBFunc = function twinChangeCommandCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Twin message received :: ", new Date()); + console.log("\nDeviceId ::: [" + deviceId + "] :: Twin message :: ", JSON.stringify(data)); + if (data.desired) { + async.forEachSeries( + Object.keys(data.desired), + function (property, callbackAtt) { + if (property == "$version") { + callbackAtt(); + } else { + var value = data.desired[property]; + iotConnectSDK.updateTwin(property, value, function (response) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Twin updated :: ", new Date()); + console.log("\nDeviceId ::: [" + deviceId + "] :: Twin updated :: ", JSON.stringify(response)); + }); + callbackAtt(); + } + }, + function () {} + ); + } +}; + +var setReadline = function setReadline(attr, type, callback) { + if (type == 1) var space = " "; + else var space = ""; + rl.question(space + "Enter " + attr + " : ", function (value) { + var obj = {}; + obj[attr] = value; + callback(obj); + }); +}; + +var callAgain = function callAgain() { + rl.question("\nDeviceId ::: [" + deviceId + "] :: Would you like to send data again ? (Y/N) : ", function (status) { + if (status == "Y" || status == "y") { + try { + getAttributes(); + } catch (error) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Get attribute error :: ", error.message, " :: ", new Date()); + } + } else process.exit(); + }); +}; + +var SendData = function SendData(sensorData) { + var sendTeleData = []; + var cnt = 0; + var text = ""; + var tagArray = []; + if (sensorData.length > 0) { + try { + async.forEachSeries( + sensorData, + function (inputData, data_cb) { + if (cnt == 0 && inputData.device.tg) { + console.log("Note :: It includes the single device from each tag."); + text = "(Gateway Device) "; + } else { + text = ""; + } + if (inputData["attributes"].length > 0) { + if (tagArray.indexOf(inputData.device.tg) == -1) { + tagArray.push(inputData.device.tg); + if (inputData.device.tg) console.log("\n## TAG :: " + inputData.device.tg + " [Device " + text + ":: " + inputData.device.id + "]"); + else console.log("\n## Device " + text + ":: " + inputData.device.id); + var senderDataObj = { + childId: cnt != 0 ? inputData.device.id : undefined, + data: {}, + }; + async.forEachSeries( + inputData.attributes, + function (attr, attrData_cb) { + if (attr.d) { + console.log("Enter " + attr.ln + " : "); + senderDataObj.data[attr.ln] = {}; + async.forEachSeries( + attr.d, + function (attrChild, attrDataChild_cb) { + setReadline(attr.ln + "." + attrChild.ln, 1, function (resultData) { + senderDataObj.data[attr.ln][attrChild.ln] = resultData[attr.ln + "." + attrChild.ln]; + attrDataChild_cb(); + }); + }, + function () { + attrData_cb(); + } + ); + } else { + setReadline(attr.ln, 0, function (resultData) { + senderDataObj.data[attr.ln] = resultData[attr.ln]; + attrData_cb(); + }); + } + }, + function () { + sendTeleData.push(senderDataObj); + cnt++; + data_cb(); + } + ); + } else { + data_cb(); + } + } + }, + function () { + // sendTeleData["time"] = new Date(); + var data = sendTeleData; + // console.log("SendData -> data example :: ", data) + iotConnectSDK.sendData(data); + setTimeout(function () { + callAgain(); + }, 500); + } + ); + } catch (error) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Send data error :: ", error.message, " :: ", new Date()); + } + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Send data fail :: No Attribute data found :: ", new Date()); + } +}; + +var attributeUpdatedCBFunc = function attributeUpdatedCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Attribute Updated :: ", new Date()); + // console.log("\nDeviceId ::: [" + deviceId + "] :: Attribute Updated :: ", JSON.stringify(data)); + if (data) getAttributes(); +}; + +// Callback function for the device updated +var deviceUpdatedCBFunc = function deviceUpdatedCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Device Updated :: ", new Date()); + //console.log("\nDeviceId ::: [" + deviceId + "] :: Devices updated :: ", JSON.stringify(data)); +}; + +// Callback function for the device updated +var ruleUpdatedCBFunc = function ruleUpdatedCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Rule Updated :: ", new Date()); + //console.log(""\nDeviceId ::: [" + deviceId + "] :: Rule updated :: ", JSON.stringify(data)); +}; + +// Callback function to receive OTA command +var OTACommandCBFunc = function OTACommandCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Receive OTA command :: ", new Date()); + if (data && data.ct == 1 && data.ack) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Received OTA command :: ", JSON.stringify(data)); + // console.log("\n"+"--- Device Command Received ---"); + var ackGuid = data.ack; + var status = 0; + var msg = "Success"; + //console.log("\nAttributes received :: ", childGlobal); + //var childId = childGlobal ? childGlobal : null; + childGlobal.forEach((c) => { + iotConnectSDK.sendAckOTA(ackGuid, status, msg, c); + }); + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Received OTA Command :: No ack :: ", JSON.stringify(data)); + } +}; + +// Callback function to receive the module information +var moduleCommandCBFunc = function moduleCommandCBFunc(data) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Module Command :: ", new Date()); + console.log("\nDeviceId ::: [" + deviceId + "] :: Module command :: ", JSON.stringify(data)); + if (data && data.ct == 2 && data.ack) { + var ackGuid = data.ack; + var status = 0; + var msg = "Success"; + iotConnectSDK.sendAckModule(ackGuid, status, msg); + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Module Command :: No ack :: ", JSON.stringify(data)); + } +}; + +var initCallbacks = function initCallbacks() { + iotConnectSDK.onTwinChangeCommand(twinChangeCommandCBFunc); + iotConnectSDK.onDeviceCommand(deviceCommandCBFunc); + iotConnectSDK.onOTACommand(OTACommandCBFunc); + iotConnectSDK.onAttrChangeCommand(attributeUpdatedCBFunc); + iotConnectSDK.onDeviceChangeCommand(deviceUpdatedCBFunc); + iotConnectSDK.onModuleCommand(moduleCommandCBFunc); + iotConnectSDK.onRuleChangeCommand(ruleUpdatedCBFunc); + + // For 2.1 + // iotConnectSDK.getCreateChildDeviceCallback(createDeviceCallback); + // iotConnectSDK.getDeleteChildDeviceCallback(deleteDeviceCallback); +}; + +// New Methods +var createChildDevice = function createChildDevice() { + var deviceId = "fn02"; + var deviceTag = "fan"; + var displayName = "Kitchen fan"; + iotConnectSDK.createChildDevice(deviceId, deviceTag, displayName, function (response) { + try { + console.log("\nDeviceId ::: [" + deviceId + "] :: Create child device status :: ", response.status, " :: ", new Date()); + } catch (error) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Create child device :: Error :: ", error.message, " :: ", new Date()); + } + }); +}; + +var deleteChildDevice = function deleteChildDevice() { + var deviceId = "fn02"; + iotConnectSDK.deleteChildDevice(deviceId, function (response) { + try { + console.log("\nDeviceId ::: [" + deviceId + "] :: Delete child device status :: ", response.status, " :: ", new Date()); + } catch (error) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Delete child device :: Error :: ", error.message, " :: ", new Date()); + } + }); +}; + +var disconnectDevice = function disconnectDevice() { + if (isDeviceConnected) { + iotConnectSDK.disconnect(); + console.log("\nDeviceId ::: [" + deviceId + "] :: Device disconnected :: ", new Date()); + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Device is already disconnected :: ", new Date()); + } +}; + +var dispose = function dispose() { + iotConnectSDK = undefined; + console.log("\nDeviceId ::: [" + deviceId + "] :: SDK object destroy :: ", new Date()); +}; + +var getTwins = function getTwins() { + if (isDeviceConnected) { + iotConnectSDK.getTwins(function (response) { + console.log("\nDeviceId ::: [" + deviceId + "] :: Get twin request sent status :: ", response.status, " :: ", new Date()); + }); + } else { + console.log("\nDeviceId ::: [" + deviceId + "] :: Get twin request :: Device is already disconnected :: ", new Date()); + } +}; diff --git a/sample/firmware.js b/sample/firmware.js new file mode 100644 index 0000000..e3067ae --- /dev/null +++ b/sample/firmware.js @@ -0,0 +1,433 @@ +"use strict"; + +/* +Hope you have installed the node SDK as guided on SDK documentation. +*/ +var SDKClient = require("iotconnect-sdk"); +var async = require("async"); +var dataInterval = null; + +/* +## Prerequisite parameter to run this sampel code +- cpId :: It need to get from the IoTConnect platform "Settings->Key Vault". +- uniqueId :: Its device ID which register on IotConnect platform and also its status has Active and Acquired +- env :: It need to get from the IoTConnect platform "Settings->Key Vault". +- dataSendInterval :: send data frequency in seconds +- disconnectDuration:: Device connection close after defined time in seconds to call dispose() method. Keep "0" if don't need disconnect the device. +- sdkOptions :: It helps to define the path of self signed and CA signed certificate as well as define the offlinne storagr params +- pf :: It can be either `aws` of `az`. +*/ + +// var uniqueId = "<>"; +// var sId = "<>"; +// var cpId = "<>"; +// var env = "<>"; +// var pf = "<>"; + +var dataSendInterval = 60; // send data frequency in seconds +var disconnectDuration = 0; //Seconds // Keep "0" If no need to disconnect +var isDeviceConnected = false; + +/* + Note: sdkOptions is optional. Mandatory for "certificate" X.509 device authentication type and discoveryUrl. + + "certificate": //For SSL CA signed and SelfSigned authorized device only otherwise skip this property + - SSLKeyPath: your device key + - SSLCertPath: your device certificate + - SSLCaPath : Root CA certificate + "offlineStorage": It helps, store the data in log file which will be created beside the firmware sample file. So, make sure your root directory has proper permission to create the log files and folder. It will store offline data once device lost the network connection. + - disabled : false = offline data storing, true = not storing offline data (Default = false) + - availSpaceInMb : Define the file size of offline data which should be in (MB) (Default = unlimited) + - fileCount : Number of file need to create for offline data (Default = 1) + + Note: It will create 5 files of 2 MB. + Define setting or leave it blank. It will set the default setting for offline storage configuration as per defined below. It may harm your device by storing the large data. Once memory get full may chance to your device script crash and stop the execution. +*/ + +var sdkOptions = { + certificate: { + SSLCertPath: "", //"<>/device.pem", + SSLKeyPath: "", //"<>/device.key", + SSLCaPath: "", //"<>/ms.pem" + }, + offlineStorage: { + disabled: false, //default value = false, false = store data, true = not store data + availSpaceInMb: 1, //in MB Default value = unlimited + fileCount: 5, // Default value = 1 + }, + // "debug" : true, // Private setting, false(default) = Don't show log, true = Show log + // "discoveryURL": <>, // Private setting, Default = "https://discovery.iotconnect.io" + skipValidation: false, // false(default) = Do validation, true = skip validation + keepalive: "", // Integer value only + cpId: cpId, + env: env, + pf: pf, +}; +var isDeviceConnected = false; + +/* +Type : Object Initialization "new SDKClient()" +Usage : To Initialize SDK and Device cinnection +Output : Callback methods for command and twin properties +Input : cpId, uniqueId, sdkOptions, env as explained above and deviceCallback and twinUpdateCallback is callback functions +*/ +var iotConnectSDK = ""; +setTimeout(() => { + if (!isDeviceConnected) { + async.series( + [ + function (cb1) { + iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, function (response) { + cb1(null, "one"); + if (response.status) { + iotConnectSDK.connect(successCallback, failedCallback, connectionStatusCallback); + } else { + console.log("DeviceId ::: [" + uniqueId + "] :: SDK initialization failed :: ", new Date()); + } + }); + }, + function (cb2) { + initCallbacks(); + cb2(null, "two"); + }, + ], + () => {} + ); + } else { + console.log("Device is already connected"); + } +}, 1000); + +// success callback +var successCallback = function successCallback(responseMessage) { + isDeviceConnected = true; + console.log("\nDeviceId ::: [" + uniqueId + "] :: Connection success :: " + responseMessage + " :: ", new Date()); +}; + +// Failed callback +var failedCallback = function failedCallback(responseMessage) { + isDeviceConnected = false; + console.log("\nDeviceId ::: [" + uniqueId + "] :: Connection failed :: " + responseMessage + " :: ", new Date()); +}; + +// Callback function for the connection status +var connectionStatusCallback = (response) => { + if (response.command) { + isDeviceConnected = true; + setTimeout(() => { + getAttributes(); + // getChildDevices(); + // createChildDevice(); + // deleteChildDevice(); + // getTwins(); + }, 10000); + console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Connected :: ", new Date()); + } else { + isDeviceConnected = false; + console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Disconnected :: ", new Date()); + } +}; + +/* +Type : Callback Function "deviceCallback()" +Usage : Firmware will receive commands from cloud. You can manage your business logic as per received command. +Output : Receive device command, firmware command and other device initialize error response +Input : +*/ + +var deviceCallback = function deviceCallback(data) { + console.log("\nDeviceId ::: [" + uniqueId + "] :: Device Command :: ", new Date()); + console.log("\nDeviceId ::: [" + uniqueId + "] :: Device command :: ", JSON.stringify(data)); + if (data && data.ct == 0 && data.ack) { + var ackGuid = data.ack; + var status = 7; // Failed = 4, Executed = 5, Success = 7 + var msg = "Success"; + var childId = data.id ? data.id : null; + iotConnectSDK.sendAckCmd(ackGuid, status, msg, childId); + } else { + console.log("\nDeviceId ::: [" + uniqueId + "] :: Device Command :: No ack :: ", JSON.stringify(data)); + } +}; + +/* +Type : Public Method "getAllTwins()" +Usage : To get all the twin properies Desired and Reported +Output : All twin property will receive in above callback function "twinUpdateCallback()" +*/ +// setTimeout(() => { +// iotConnectSDK.getTwins(function (response) { +// console.log("get Twins ==> response ", ); +// }); +// }, 15000); + +/* +Type : Callback Function "twinUpdateCallback()" +Usage : Manage twin properties as per business logic to update the twin reported property +Output : Receive twin properties Desired, Reported +*/ +var twinUpdateCallback = function twinUpdateCallback(data) { + // console.log("\n--- Twin desired message received ---"); + // console.log(data); + if (data.desired) { + async.forEachSeries( + Object.keys(data.desired), + function (key, callbackatt) { + if (key == "$version") { + callbackatt(); + } else { + var value = data.desired[key]; + if (iotConnectSDK) { + iotConnectSDK.updateTwin(key, value, (obj) => { + // console.log(obj); + }); + } else { + console.log("Connection object not founud"); + } + callbackatt(); + } + }, + function () {} + ); + } +}; + +/* +Type : Public Method "updateTwin()" +Usage : Upate the twin reported property +Output : +Input : "key" and "value" as below + // var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message + // var value = "<< Desired Property value >>"; // Value of respective desired property +*/ +//iotConnectSDK.updateTwin(key,value) + +/* +Type : Public Method "sendData()" +Usage : To publish the D2C data +Output : +Input : Predefined data object +*/ + +/* +Type : Public Method "dispose()" +Usage : Disconnect the device from cloud +Output : +Input : +Note : It will disconnect the device after defined time +*/ +if (disconnectDuration && disconnectDuration > 0) { + setTimeout(() => { + if (iotConnectSDK && isDeviceConnected == true) { + iotConnectSDK.dispose(); + isDeviceConnected = false; + } else { + console.log("Connection object not founud"); + } + }, eval(disconnectDuration * 1000)); +} + +// Callback function for the connection status +var connectionStatusChanged = function connectionStatusChanged(data) { + // console.log("connection status => ", data); + if (data.ct == 3) { + console.log("\n" + "--- Device connection status --- ", data.command); + // console.log(data); + try { + if (data.command) { + isDeviceConnected = true; + setTimeout(() => { + getAttributes(); + getDevices(); + // iotConnectSDK.getAllTwins(); + // createChildDevice(); + // deleteChildDevice(); + }, 10000); + } else { + isDeviceConnected = false; + } + } catch (error) { + console.log("Error while getting attributes :: ", error.message); + } + } else { + console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Wrong command :: ", new Date()); + } +}; + +// Callback function for the Attribute updated +var attributeUpdated = function attributeUpdated(data) { + console.log("\nDeviceId ::: [" + uniqueId + "] :: Attribute Updated :: ", JSON.stringify(data, null, 2)); + if (data) getAttributes(); +}; + +var childGlobal = []; +var getAttributes = function getAttributes() { + iotConnectSDK.getAttributes(function (response) { + try { + if (response.data && response.data instanceof Array && response.data.length) { + childGlobal = response.data.map((e) => e.device.id); + } + if (dataInterval) { + clearInterval(dataInterval); + } + dataInterval = setInterval(() => { + // Non Gateway + var data = [ + { + uniqueId: uniqueId, + time: new Date(), + data: { + // Add your device attributes and respective value here as per standard format defined in sdk documentation + int1: getRandomValue(1, 50), + // "long1":31, + // "integer1":55, + // "decimal1":0.555, + // "time1":"11:55:22", + // "bit1":2, + // "latlong1":"["+getRandomValue(-90, 90)+","+getRandomValue(-180, 180)+"]", + // "string1":"red", + // "gyro": { + // 'bit1':0.1, + // "decimal1":2.555, + // "integer1":884, + // "latlong1":"["+getRandomValue(-90, 90)+","+getRandomValue(-180, 180)+"]", + // "long1":999, + // "string1":"green", + // "time1":"11:44:22", + // "temperature":200 + // } + }, + }, + ]; + + // Gateway Device + // var data = [{ + // "uniqueId":uniqueId, + // "time":new Date(), + // "data": {"bit1":1,"Temperature": getRandomValue(1, 50),"gyro":{"x":getRandomValue(1, 50),"y":getRandomValue(1, 50),"z":getRandomValue(1, 50)}} // Add your device attributes and respective value here as per standard format defined in sdk documentation + // },{ + // "uniqueId":"v21tg201c1", + // "time":new Date(), + // "data": {"bit1":1,"Temperature": getRandomValue(1, 50)} // Add your device attributes and respective value here as per standard format defined in sdk documentation + // }] + + if (iotConnectSDK) { + // Device to Cloud data publish + iotConnectSDK.sendData(data); + } else { + console.log("Connection object not founud"); + } + }, eval(dataSendInterval * 1000)); + } catch (error) { + console.log("Error while getting attributes :: ", error); + } + }); +}; + +console.log("Nodejs Message format 2.1 SDK"); + +var getDevices = function getDevices() { + iotConnectSDK.getDevices(function (response) { + try { + console.log("response.data Devices ", JSON.stringify(response)); + // SendData(response.data); + } catch (error) { + console.log("Error while getting attributes :: ", error); + } + }); +}; + +// Callback function for the device updated +var deviceUpdated = function deviceUpdated(data) { + console.log("\nDeviceId ::: [" + uniqueId + "] :: Devices updated :: ", JSON.stringify(data)); +}; + +// Callback function to receive OTA command +var receiveOTA = function receiveOTA(data) { + if (data && data.ct == 1 && data.ack) { + console.log("\nUniqueId ::: [" + uniqueId + "] :: Received OTA command :: ", new Date(), JSON.stringify(data)); + var ackGuid = data.ack; + var status = 0; + var msg = "Success"; + console.log("\nAttributes received :: ", childGlobal); + //var childId = childGlobal ? childGlobal : null; + childGlobal.forEach((c) => { + iotConnectSDK.sendAckOTA(ackGuid, status, msg, c); + }); + } else { + console.log("\nUniqueId ::: [" + uniqueId + "] :: Received OTA Command :: No ack :: ", JSON.stringify(data)); + } +}; + +// Callback function to receive the module information +var moduleReceived = function moduleReceived(data) { + console.log("module received => ", data); + if (data && data.ct == 1) { + var obj = { + ack: data.ack, + type: data.ct, + msg: "Success", + cid: "", // For gatewat device only for child device + }; + // var msgType = 6; + if (data.ack != null) { + var bool = 1; + iotConnectSDK.sendAckModule(bool, obj); + } + } else { + console.log("Wrong command "); + } +}; + +var initCallbacks = function initCallbacks() { + if (iotConnectSDK) { + iotConnectSDK.setConnectionStatusChangedCallback(connectionStatusChanged); + iotConnectSDK.setTwinChangedCallback(twinUpdateCallback); + iotConnectSDK.setDeviceCommandCallback(deviceCallback); + iotConnectSDK.setOTAReceivedCallback(receiveOTA); + iotConnectSDK.setAttributeChangedCallback(attributeUpdated); + iotConnectSDK.setDeviceChangedCallback(deviceUpdated); + iotConnectSDK.setModuleReceivedCallback(moduleReceived); + } + // For 2.1 + // iotConnectSDK.getCreateChildDeviceCallback(createDeviceCallback); + // iotConnectSDK.getDeleteChildDeviceCallback(deleteDeviceCallback); +}; + +// New Methods +var createChildDevice = function createChildDevice() { + var deviceId = "ac001"; + var deviceTag = "child12"; + var displayName = "AC badroom"; + iotConnectSDK.createChildDevice(deviceId, deviceTag, displayName, function (response) { + try { + console.log("Create child device request :: ", response); + } catch (error) { + console.log("Error while create child device :: ", error.message); + } + }); +}; + +var deleteChildDevice = function deleteChildDevice() { + var deviceId = "ac00111"; + iotConnectSDK.deleteChildDevice(deviceId, function (response) { + try { + console.log("Delete child device request :: ", response); + } catch (error) { + console.log("Error while delete child device :: ", error.message); + } + }); +}; + +/* +Type : Function "getRandomValue()" +Usage : To generate the random value for simulated data +Input : It will gives random number between min and max range. +Output : Random number +x`*/ +function getRandomValue(min, max) { + return (Math.random() * (max - min) + min).toFixed(0); +} + +function getRandomDecimalValue(min, max, precision) { + return (Math.random() * (max - min) + min).toFixed(precision || 2); +} diff --git a/sample/mqtt/example.js b/sample/mqtt/example.js deleted file mode 100644 index 29d4efb..0000000 --- a/sample/mqtt/example.js +++ /dev/null @@ -1,429 +0,0 @@ -'use strict'; - -var SDKClient = require('iotconnect-sdk'); -var iotConnectSDK = ""; -var readline = require('readline'); -var async = require('async'); -var fs = require('fs-extra'); -var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); -var sdkOptions = { - // "certificate" : { // Self signed or CA signed device only - // "SSLKeyPath" : "/var/www/html/sdk-msg-2.1/sw-tt-iotconnect-sdk-node/sample/mqtt/crt/hliotShpere01/device.key", - // "SSLCertPath" : "/var/www/html/sdk-msg-2.1/sw-tt-iotconnect-sdk-node/sample/mqtt/crt/hliotShpere01/device.pem", - // "SSLCaPath" : "/var/www/html/sdk-msg-2.1/sw-tt-iotconnect-sdk-node/sample/mqtt/crt/hliotShpere01/rootCA.pem" - // }, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimited - "fileCount": 5 // Default value = 1 - }, - "debug" : false, // Private setting, false(default) = Don't show log, true = Show log - //"discoveryURL": "", // Private setting, Default = "https://discovery.iotconnect.io" - // "devicePK": "ZmpmZ2pmZ2pmZ2pmZ2pmZ2pmZ2pmZ2pnampmZ2pmZ2pmZ25nZGRnaHJzZ3JocXJ3ZXJ3cjQzNTM0NjYzNDY1Ng==", // For Symmetric Key Auth type support - "skipValidation": false, // false(default) = Do validation, true = skip validation - "keepalive": "", // Integer value only - "dpsInfo": { // For TPM device only - "scopeId": "", - "globalEndpoint": "" - } -} -var isDeviceConnected = false; - -var deviceId = "<>"; -var sIdd = "<>"; - -async.series([ - function(cb_series) { - rl.question('Enter device serial number : ', function (uniqueId) { - uniqueId = deviceId; - rl.question('Enter SID : ', function (sId) { - sId = sIdd; - if(sdkOptions.certificate){ - try { - var CERT_PATH_FLAG = true; - async.forEachSeries(Object.values(sdkOptions.certificate), function (filePath, cb_inner) { - if(!fs.existsSync(filePath)) { - CERT_PATH_FLAG = false; - } - cb_inner(); - }, function () { - if(CERT_PATH_FLAG == true) { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, initCallback); - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Device is already connected :: ", new Date()); - } - cb_series(); - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Set proper certificate file path and try again :: ", new Date()); - process.exit(); - } - }); - } catch (error) { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: error :: ", error.message," :: ", new Date()); - } - } else { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, initCallback); - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Device is already connected :: ", new Date()); - } - cb_series(); - } - }); - }); - } -], function(err, response) { }) - -var initCallback = function initCallback(response) { - if(response.status){ - startConnection(); - initCallbacks(); - console.log("DeviceId ::: [" + deviceId + "] :: SDK initialization Success :: ", new Date()); - } else { - console.log("DeviceId ::: [" + deviceId + "] :: SDK initialization failed ::",response.message," :: ", new Date()); - } -} - -var startConnection = function startConnection() { - iotConnectSDK.connect(successCallback, failedCallback, connectionStatusCallback) -} - -// success callback -var successCallback = function successCallback(responseMessage){ - isDeviceConnected = true; - console.log("\nDeviceId ::: [" + deviceId + "] :: Connection success :: "+responseMessage+" :: ", new Date()); -} - -// Failed callback -var failedCallback = function failedCallback(responseMessage){ - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + deviceId + "] :: Connection failed :: "+responseMessage+" :: ", new Date()); -} - -// Callback function for the connection status -var connectionStatusCallback = function connectionStatusCallback(response){ - if(response.command) { - isDeviceConnected = true; - setTimeout(() => { - getAttributes(); - // getChildDevices(); - // createChildDevice(); - // deleteChildDevice(); - // getTwins(); - }, 10000); - console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Disconnected :: ", new Date()); - } -} - -var childGlobal = []; -var getAttributes = function getAttributes(){ - iotConnectSDK.getAttributes(function(response){ - try { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get Attributes :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Attributes received :: ", JSON.stringify(response)); - - if(response.data && response.data instanceof Array && response.data.length){ - childGlobal = response.data.map(e => e.device.id); - } - SendData(response.data); - } catch (error) { - console.log("Error while getting attributes :: ",error); - } - }) -} - -var getChildDevices = function getChildDevices(){ - iotConnectSDK.getChildDevices(function(response){ - try { - if(response.status) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices received :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices :: ", JSON.stringify(response)); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices receive request failed :: ",response.message," :: ", new Date()); - } - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices receive request failed :: ",error.message," :: ", new Date()); - } - }) -} - -var deviceCommandCBFunc = function deviceCommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Device Command :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Device command :: ", JSON.stringify(data)); - if(data && data.ct == 0 && data.ack) { - var ackGuid = data.ack; - var status = 7; // Failed = 4, Executed = 5, Success = 7 - var msg = "Success"; - var childId = data.id ? data.id : null; - iotConnectSDK.sendAckCmd(ackGuid, status, msg, childId); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Device Command :: No ack :: ", JSON.stringify(data)); - } -} - -var twinChangeCommandCBFunc = function twinChangeCommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin message received :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin message :: ", JSON.stringify(data)); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (property, callbackAtt) { - if(property == "$version"){ - callbackAtt(); - } else { - var value = data.desired[property]; - iotConnectSDK.updateTwin(property, value, function (response) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin updated :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin updated :: ", JSON.stringify(response)); - }) - callbackAtt(); - } - }, function () { }) - } -} - -var setReadline = function setReadline (attr, type, callback){ - if(type == 1) - var space = " "; - else - var space = ""; - rl.question(space+'Enter '+attr+' : ', function (value) { - var obj = {}; - obj[attr] = value; - callback(obj); - }); -} - -var callAgain = function callAgain (){ - rl.question("\nDeviceId ::: [" + deviceId + "] :: Would you like to send data again ? (Y/N) : ", function (status) { - if(status == "Y" || status == "y") - { - try { - getAttributes(); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get attribute error :: ", error.message, " :: ", new Date()); - } - } - else - process.exit(); - }); -} - -var SendData = function SendData(sensorData){ - var sendTeleData = []; - var cnt = 0; - var text = ""; - var tagArray = []; - if(sensorData.length > 0) { - - try { - async.forEachSeries(sensorData, function(inputData, data_cb) { - if(cnt == 0 && inputData.device.tg) { - console.log("Note :: It includes the single device from each tag."); - text = "(Gateway Device) "; - } else { - text = ""; - } - if(inputData['attributes'].length > 0) - { - if (tagArray.indexOf(inputData.device.tg) == -1) { - tagArray.push(inputData.device.tg); - if(inputData.device.tg) - console.log("\n## TAG :: "+inputData.device.tg+" [Device "+text+":: "+inputData.device.id+"]"); - else - console.log("\n## Device "+text+":: "+inputData.device.id); - var senderDataObj = { - "childId": cnt != 0 ? inputData.device.id : undefined, - "data": {} - } - async.forEachSeries(inputData.attributes, function(attr, attrData_cb) { - if(attr.d) - { - console.log("Enter "+attr.ln+" : "); - senderDataObj.data[attr.ln] = {}; - async.forEachSeries(attr.d, function(attrChild, attrDataChild_cb) { - setReadline(attr.ln+'.'+attrChild.ln, 1, function(resultData){ - senderDataObj.data[attr.ln][attrChild.ln] = resultData[attr.ln+'.'+attrChild.ln]; - attrDataChild_cb() - }); - },function(){ - attrData_cb() - }); - } - else - { - setReadline(attr.ln, 0, function(resultData){ - senderDataObj.data[attr.ln] = resultData[attr.ln]; - attrData_cb(); - }); - } - },function(){ - sendTeleData.push(senderDataObj); - cnt++; - data_cb(); - }); - } else { - - data_cb(); - } - } - },function(){ - // sendTeleData["time"] = new Date(); - var data = sendTeleData; - // console.log("SendData -> data example :: ", data) - iotConnectSDK.sendData(data); - setTimeout(function() { - callAgain(); - }, 500); - }); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Send data error :: ", error.message, " :: ", new Date()); - } - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Send data fail :: No Attribute data found :: ", new Date()); - } -} - -var attributeUpdatedCBFunc = function attributeUpdatedCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Attribute Updated :: ", new Date()); - // console.log("\nDeviceId ::: [" + deviceId + "] :: Attribute Updated :: ", JSON.stringify(data)); - if(data) - getAttributes(); -} - -// Callback function for the device updated -var deviceUpdatedCBFunc = function deviceUpdatedCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Device Updated :: ", new Date()); - //console.log("\nDeviceId ::: [" + deviceId + "] :: Devices updated :: ", JSON.stringify(data)); -} - -// Callback function for the device updated -var ruleUpdatedCBFunc = function ruleUpdatedCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Rule Updated :: ", new Date()); - //console.log(""\nDeviceId ::: [" + deviceId + "] :: Rule updated :: ", JSON.stringify(data)); -} - -// Callback function to receive OTA command -var OTACommandCBFunc = function OTACommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Receive OTA command :: ", new Date()); - if(data && data.ct == 1 && data.ack) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Received OTA command :: ", JSON.stringify(data)); - // console.log("\n"+"--- Device Command Received ---"); - var ackGuid = data.ack; - var status = 0; - var msg = "Success"; - //console.log("\nAttributes received :: ", childGlobal); - //var childId = childGlobal ? childGlobal : null; - childGlobal.forEach(c => { - iotConnectSDK.sendAckOTA(ackGuid, status, msg, c); - }) - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Received OTA Command :: No ack :: ", JSON.stringify(data)); - } -} - -// Callback function to receive the module information -var moduleCommandCBFunc = function moduleCommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Module Command :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Module command :: ", JSON.stringify(data)); - if(data && data.ct == 2 && data.ack) { - var ackGuid = data.ack; - var status = 0; - var msg = "Success"; - iotConnectSDK.sendAckModule(ackGuid, status, msg); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Module Command :: No ack :: ", JSON.stringify(data)); - } -} - -var initCallbacks = function initCallbacks(){ - iotConnectSDK.onTwinChangeCommand(twinChangeCommandCBFunc); - iotConnectSDK.onDeviceCommand(deviceCommandCBFunc); - iotConnectSDK.onOTACommand(OTACommandCBFunc); - iotConnectSDK.onAttrChangeCommand(attributeUpdatedCBFunc); - iotConnectSDK.onDeviceChangeCommand(deviceUpdatedCBFunc); - iotConnectSDK.onModuleCommand(moduleCommandCBFunc); - iotConnectSDK.onRuleChangeCommand(ruleUpdatedCBFunc); - - // For 2.1 - // iotConnectSDK.getCreateChildDeviceCallback(createDeviceCallback); - // iotConnectSDK.getDeleteChildDeviceCallback(deleteDeviceCallback); -} - -// New Methods -var createChildDevice = function createChildDevice(){ - var deviceId = "fn02"; - var deviceTag = "fan"; - var displayName = "Kitchen fan"; - iotConnectSDK.createChildDevice(deviceId, deviceTag, displayName, function(response){ - try { - console.log("\nDeviceId ::: [" + deviceId + "] :: Create child device status :: ", response.status ," :: ", new Date()); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Create child device :: Error :: ",error.message, " :: ", new Date()); - } - }) -} - -var deleteChildDevice = function deleteChildDevice(){ - var deviceId = "fn02"; - iotConnectSDK.deleteChildDevice(deviceId, function(response){ - try { - console.log("\nDeviceId ::: [" + deviceId + "] :: Delete child device status :: ", response.status ," :: ", new Date()); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Delete child device :: Error :: ",error.message, " :: ", new Date()); - } - }) -} - -var disconnectDevice = function disconnectDevice(){ - if(isDeviceConnected) { - iotConnectSDK.disconnect(); - console.log("\nDeviceId ::: [" + deviceId + "] :: Device disconnected :: ", new Date()); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Device is already disconnected :: ", new Date()); - } -} - -var dispose = function dispose(){ - iotConnectSDK = undefined; - console.log("\nDeviceId ::: [" + deviceId + "] :: SDK object destroy :: ", new Date()); -} - -var getTwins = function getTwins(){ - if(isDeviceConnected) { - iotConnectSDK.getTwins(function (response) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get twin request sent status :: ", response.status ," :: ", new Date()); - }); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get twin request :: Device is already disconnected :: ", new Date()); - } -} - -//*** */ To connect the device *** -// setTimeout(() => { -// startConnection(); -// }, 30000); - -// *** */ To disconnect the device *** -// setTimeout(() => { -// disconnectDevice(); -// }, 15000); - -//*** */ To discard the SDK object the device *** -// setTimeout(() => { -// dispose(); -// }, 50000); - -// setTimeout(() => { -// console.log("Retry disconnect call..."); -// try { -// disconnectDevice(); -// } catch (error) { -// console.log(error); -// } -// }, 60000); \ No newline at end of file diff --git a/sample/mqtt/example1.js b/sample/mqtt/example1.js deleted file mode 100644 index 98f9827..0000000 --- a/sample/mqtt/example1.js +++ /dev/null @@ -1,430 +0,0 @@ -'use strict'; - -var SDKClient = require('iotconnect-sdk'); -var iotConnectSDK = ""; -var readline = require('readline'); -var async = require('async'); -var fs = require('fs-extra'); -var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); -var sdkOptions = { - // "certificate" : { // Self signed or CA signed device only - // "SSLKeyPath" : "", - // "SSLCertPath" : "", - // "SSLCaPath" : "" - // }, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimited - "fileCount": 5 // Default value = 1 - }, - "debug" : true, // Private setting, false(default) = Don't show log, true = Show log - //"discoveryURL": "", // Private setting, Default = "https://discovery.iotconnect.io" - // "devicePK": "", // For Symmetric Key Auth type support - "skipValidation": false, // false(default) = Do validation, true = skip validation - "keepalive": "", // Integer value only - "dpsInfo": { // For TPM device only - "scopeId": "", - "globalEndpoint": "" - } -} -var isDeviceConnected = false; - - -var deviceId = "<>"; -var sIdd = "<>"; - -async.series([ - function(cb_series) { - rl.question('Enter device serial number : ', function (uniqueId) { - uniqueId = deviceId; - rl.question('Enter SID : ', function (sId) { - sId = sIdd; - if(sdkOptions.certificate){ - try { - var CERT_PATH_FLAG = true; - async.forEachSeries(Object.values(sdkOptions.certificate), function (filePath, cb_inner) { - if(!fs.existsSync(filePath)) { - CERT_PATH_FLAG = false; - } - cb_inner(); - }, function () { - if(CERT_PATH_FLAG == true) { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, initCallback); - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Device is already connected :: ", new Date()); - } - cb_series(); - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Set proper certificate file path and try again :: ", new Date()); - process.exit(); - } - }); - } catch (error) { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: error :: ", error.message," :: ", new Date()); - } - } else { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, initCallback); - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: Init :: Device is already connected :: ", new Date()); - } - cb_series(); - } - }); - }); - } -], function(err, response) { }) - -var initCallback = function initCallback(response) { - if(response.status){ - startConnection(); - initCallbacks(); - console.log("DeviceId ::: [" + deviceId + "] :: SDK initialization Success :: ", new Date()); - } else { - console.log("DeviceId ::: [" + deviceId + "] :: SDK initialization failed ::",response.message," :: ", new Date()); - } -} - -var startConnection = function startConnection() { - iotConnectSDK.connect(successCallback, failedCallback, connectionStatusCallback) -} - -// success callback -var successCallback = function successCallback(responseMessage){ - isDeviceConnected = true; - console.log("\nDeviceId ::: [" + deviceId + "] :: Connection success :: "+responseMessage+" :: ", new Date()); -} - -// Failed callback -var failedCallback = function failedCallback(responseMessage){ - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + deviceId + "] :: Connection failed :: "+responseMessage+" :: ", new Date()); -} - -// Callback function for the connection status -var connectionStatusCallback = function connectionStatusCallback(response){ - if(response.command) { - isDeviceConnected = true; - setTimeout(() => { - getAttributes(); - // getChildDevices(); - // createChildDevice(); - // deleteChildDevice(); - // getTwins(); - }, 10000); - console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Disconnected :: ", new Date()); - } -} - -var childGlobal = []; -var getAttributes = function getAttributes(){ - iotConnectSDK.getAttributes(function(response){ - try { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get Attributes :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Attributes received :: ", JSON.stringify(response)); - - if(response.data && response.data instanceof Array && response.data.length){ - childGlobal = response.data.map(e => e.device.id); - } - SendData(response.data); - } catch (error) { - console.log("Error while getting attributes :: ",error); - } - }) -} - -var getChildDevices = function getChildDevices(){ - iotConnectSDK.getChildDevices(function(response){ - try { - if(response.status) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices received :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices :: ", JSON.stringify(response)); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices receive request failed :: ",response.message," :: ", new Date()); - } - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Child devices receive request failed :: ",error.message," :: ", new Date()); - } - }) -} - -var deviceCommandCBFunc = function deviceCommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Device Command :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Device command :: ", JSON.stringify(data)); - if(data && data.ct == 0 && data.ack) { - var ackGuid = data.ack; - var status = 7; // Failed = 4, Executed = 5, Success = 7 - var msg = "Success"; - var childId = data.id ? data.id : null; - iotConnectSDK.sendAckCmd(ackGuid, status, msg, childId); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Device Command :: No ack :: ", JSON.stringify(data)); - } -} - -var twinChangeCommandCBFunc = function twinChangeCommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin message received :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin message :: ", JSON.stringify(data)); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (property, callbackAtt) { - if(property == "$version"){ - callbackAtt(); - } else { - var value = data.desired[property]; - iotConnectSDK.updateTwin(property, value, function (response) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin updated :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Twin updated :: ", JSON.stringify(response)); - }) - callbackAtt(); - } - }, function () { }) - } -} - -var setReadline = function setReadline (attr, type, callback){ - if(type == 1) - var space = " "; - else - var space = ""; - rl.question(space+'Enter '+attr+' : ', function (value) { - var obj = {}; - obj[attr] = value; - callback(obj); - }); -} - -var callAgain = function callAgain (){ - rl.question("\nDeviceId ::: [" + deviceId + "] :: Would you like to send data again ? (Y/N) : ", function (status) { - if(status == "Y" || status == "y") - { - try { - getAttributes(); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get attribute error :: ", error.message, " :: ", new Date()); - } - } - else - process.exit(); - }); -} - -var SendData = function SendData(sensorData){ - var sendTeleData = []; - var cnt = 0; - var text = ""; - var tagArray = []; - if(sensorData.length > 0) { - - try { - async.forEachSeries(sensorData, function(inputData, data_cb) { - if(cnt == 0 && inputData.device.tg) { - console.log("Note :: It includes the single device from each tag."); - text = "(Gateway Device) "; - } else { - text = ""; - } - if(inputData['attributes'].length > 0) - { - if (tagArray.indexOf(inputData.device.tg) == -1) { - tagArray.push(inputData.device.tg); - if(inputData.device.tg) - console.log("\n## TAG :: "+inputData.device.tg+" [Device "+text+":: "+inputData.device.id+"]"); - else - console.log("\n## Device "+text+":: "+inputData.device.id); - var senderDataObj = { - "childId": cnt != 0 ? inputData.device.id : undefined, - "data": {} - } - async.forEachSeries(inputData.attributes, function(attr, attrData_cb) { - if(attr.d) - { - console.log("Enter "+attr.ln+" : "); - senderDataObj.data[attr.ln] = {}; - async.forEachSeries(attr.d, function(attrChild, attrDataChild_cb) { - setReadline(attr.ln+'.'+attrChild.ln, 1, function(resultData){ - senderDataObj.data[attr.ln][attrChild.ln] = resultData[attr.ln+'.'+attrChild.ln]; - attrDataChild_cb() - }); - },function(){ - attrData_cb() - }); - } - else - { - setReadline(attr.ln, 0, function(resultData){ - senderDataObj.data[attr.ln] = resultData[attr.ln]; - attrData_cb(); - }); - } - },function(){ - sendTeleData.push(senderDataObj); - cnt++; - data_cb(); - }); - } else { - - data_cb(); - } - } - },function(){ - // sendTeleData["time"] = new Date(); - var data = sendTeleData; - // console.log("SendData -> data example :: ", data) - iotConnectSDK.sendData(data); - setTimeout(function() { - callAgain(); - }, 500); - }); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Send data error :: ", error.message, " :: ", new Date()); - } - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Send data fail :: No Attribute data found :: ", new Date()); - } -} - -var attributeUpdatedCBFunc = function attributeUpdatedCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Attribute Updated :: ", new Date()); - // console.log("\nDeviceId ::: [" + deviceId + "] :: Attribute Updated :: ", JSON.stringify(data)); - if(data) - getAttributes(); -} - -// Callback function for the device updated -var deviceUpdatedCBFunc = function deviceUpdatedCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Device Updated :: ", new Date()); - //console.log("\nDeviceId ::: [" + deviceId + "] :: Devices updated :: ", JSON.stringify(data)); -} - -// Callback function for the device updated -var ruleUpdatedCBFunc = function ruleUpdatedCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Rule Updated :: ", new Date()); - //console.log(""\nDeviceId ::: [" + deviceId + "] :: Rule updated :: ", JSON.stringify(data)); -} - -// Callback function to receive OTA command -var OTACommandCBFunc = function OTACommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Receive OTA command :: ", new Date()); - if(data && data.ct == 1 && data.ack) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Received OTA command :: ", JSON.stringify(data)); - // console.log("\n"+"--- Device Command Received ---"); - var ackGuid = data.ack; - var status = 0; - var msg = "Success"; - //console.log("\nTEST childglobal ::: :: Attributes received :: ", childGlobal); - //var childId = childGlobal ? childGlobal : null; - childGlobal.forEach(c => { - iotConnectSDK.sendAckOTA(ackGuid, status, msg, c); - }) - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Received OTA Command :: No ack :: ", JSON.stringify(data)); - } -} - -// Callback function to receive the module information -var moduleCommandCBFunc = function moduleCommandCBFunc(data){ - console.log("\nDeviceId ::: [" + deviceId + "] :: Module Command :: ", new Date()); - console.log("\nDeviceId ::: [" + deviceId + "] :: Module command :: ", JSON.stringify(data)); - if(data && data.ct == 2 && data.ack) { - var ackGuid = data.ack; - var status = 0; - var msg = "Success"; - iotConnectSDK.sendAckModule(ackGuid, status, msg); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Module Command :: No ack :: ", JSON.stringify(data)); - } -} - -var initCallbacks = function initCallbacks(){ - iotConnectSDK.onTwinChangeCommand(twinChangeCommandCBFunc); - iotConnectSDK.onDeviceCommand(deviceCommandCBFunc); - iotConnectSDK.onOTACommand(OTACommandCBFunc); - iotConnectSDK.onAttrChangeCommand(attributeUpdatedCBFunc); - iotConnectSDK.onDeviceChangeCommand(deviceUpdatedCBFunc); - iotConnectSDK.onModuleCommand(moduleCommandCBFunc); - iotConnectSDK.onRuleChangeCommand(ruleUpdatedCBFunc); - - // For 2.1 - // iotConnectSDK.getCreateChildDeviceCallback(createDeviceCallback); - // iotConnectSDK.getDeleteChildDeviceCallback(deleteDeviceCallback); -} - -// New Methods -var createChildDevice = function createChildDevice(){ - var deviceId = "fn02"; - var deviceTag = "fan"; - var displayName = "Kitchen fan"; - iotConnectSDK.createChildDevice(deviceId, deviceTag, displayName, function(response){ - try { - console.log("\nDeviceId ::: [" + deviceId + "] :: Create child device status :: ", response.status ," :: ", new Date()); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Create child device :: Error :: ",error.message, " :: ", new Date()); - } - }) -} - -var deleteChildDevice = function deleteChildDevice(){ - var deviceId = "fn02"; - iotConnectSDK.deleteChildDevice(deviceId, function(response){ - try { - console.log("\nDeviceId ::: [" + deviceId + "] :: Delete child device status :: ", response.status ," :: ", new Date()); - } catch (error) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Delete child device :: Error :: ",error.message, " :: ", new Date()); - } - }) -} - -var disconnectDevice = function disconnectDevice(){ - if(isDeviceConnected) { - iotConnectSDK.disconnect(); - console.log("\nDeviceId ::: [" + deviceId + "] :: Device disconnected :: ", new Date()); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Device is already disconnected :: ", new Date()); - } -} - -var dispose = function dispose(){ - iotConnectSDK = undefined; - console.log("\nDeviceId ::: [" + deviceId + "] :: SDK object destroy :: ", new Date()); -} - -var getTwins = function getTwins(){ - if(isDeviceConnected) { - iotConnectSDK.getTwins(function (response) { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get twin request sent status :: ", response.status ," :: ", new Date()); - }); - } else { - console.log("\nDeviceId ::: [" + deviceId + "] :: Get twin request :: Device is already disconnected :: ", new Date()); - } -} - -//*** */ To connect the device *** -// setTimeout(() => { -// startConnection(); -// }, 30000); - -// *** */ To disconnect the device *** -// setTimeout(() => { -// disconnectDevice(); -// }, 15000); - -//*** */ To discard the SDK object the device *** -// setTimeout(() => { -// dispose(); -// }, 50000); - -// setTimeout(() => { -// console.log("Retry disconnect call..."); -// try { -// disconnectDevice(); -// } catch (error) { -// console.log(error); -// } -// }, 60000); \ No newline at end of file diff --git a/sample/mqtt/firmware.js b/sample/mqtt/firmware.js deleted file mode 100644 index 0779d0f..0000000 --- a/sample/mqtt/firmware.js +++ /dev/null @@ -1,455 +0,0 @@ -'use strict'; - -/* -Hope you have installed the node SDK as guided on SDK documentation. -*/ -var SDKClient = require('iotconnect-sdk'); -var async = require('async'); - -/* -## Prerequisite parameter to run this sampel code -- cpId :: It need to get from the IoTConnect platform "Settings->Key Vault". -- uniqueId :: Its device ID which register on IotConnect platform and also its status has Active and Acquired -- env :: It need to get from the IoTConnect platform "Settings->Key Vault". -- dataSendInterval :: send data frequency in seconds -- disconnectDuration:: Device connection close after defined time in seconds to call dispose() method. Keep "0" if don't need disconnect the device. -- sdkOptions :: It helps to define the path of self signed and CA signed certificate as well as define the offlinne storagr params -*/ - -var uniqueId = "<>"; -var sId ="<>"; - -var dataSendInterval = 60; // send data frequency in seconds -var disconnectDuration = 0; //Seconds // Keep "0" If no need to disconnect -var isDeviceConnected = false; - -/* -Note: sdkOptions is optional. Mandatory for "certificate" X.509 device authentication type and discoveryUrl. - "certificate": //For SSL CA signed and SelfSigned authorized device only otherwise skip this property - - SSLKeyPath: your device key - - SSLCertPath: your device certificate - - SSLCaPath : Root CA certificate - "offlineStorage": It helps, store the data in log file which will be created beside the firmware sample file. So, make sure your root directory has proper permission to create the log files and folder. It will store offline data once device lost the network connection. - - disabled : false = offline data storing, true = not storing offline data (Default = false) - - availSpaceInMb : Define the file size of offline data which should be in (MB) (Default = unlimited) - - fileCount : Number of file need to create for offline data (Default = 1) - - Note : It will create 5 files of 2 MB. - Define setting or leave it blank. It will set the default setting for offline storage configuration as per defined below. It may harm your device by storing the large data. Once memory get full may chance to your device script crash and stop the execution. -*/ - -var sdkOptions = { - "certificate" : { - "SSLCertPath" : "<>", //"<>/device.pem", - "SSLKeyPath" : "<>", //"<>/device.key", - "SSLCaPath" : "<>" //"<>/ms.pem" - }, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimited - "fileCount": 5 // Default value = 1 - }, - "debug" : true, // Private setting, false(default) = Don't show log, true = Show log - "discoveryURL": "https://discovery.iotconnect.io", // Private setting, Default = "https://discovery.iotconnect.io" - // "devicePK": "cGFyYXNwYXJhc3BhcmFzcGFyYXNwYXJhc3BhcmFzcGFyYQ==", // For Symmetric Key Auth type support - "skipValidation": false, // false(default) = Do validation, true = skip validation - "keepalive": "", // Integer value only - "dpsInfo": { // For TPM device only - "scopeId": "", - "globalEndpoint": "" - } -} -var isDeviceConnected = false; - -/* -Type : Object Initialization "new SDKClient()" -Usage : To Initialize SDK and Device cinnection -Output : Callback methods for command and twin properties -Input : cpId, uniqueId, sdkOptions, env as explained above and deviceCallback and twinUpdateCallback is callback functions -*/ -var iotConnectSDK = ""; -setTimeout(() => { - debugger; - if(!isDeviceConnected) { - async.series([ - function(cb1) { - iotConnectSDK = new SDKClient(uniqueId, sId, sdkOptions, function(response){ - cb1(null, 'one'); - if(response.status){ - iotConnectSDK.connect(successCallback, failedCallback, connectionStatusCallback) - } else { - console.log("DeviceId ::: [" + uniqueId + "] :: SDK initialization failed :: ", new Date()); - } - }); - }, - function(cb2) { - initCallbacks(); - cb2(null, 'two'); - } - ], () => { - - }); - } else { - console.log("Device is already connected"); - } -}, 1000); - - -// success callback -var successCallback = function successCallback(responseMessage){ - isDeviceConnected = true; - console.log("\nDeviceId ::: [" + uniqueId + "] :: Connection success :: "+responseMessage+" :: ", new Date()); -} - -// Failed callback -var failedCallback = function failedCallback(responseMessage){ - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + uniqueId + "] :: Connection failed :: "+responseMessage+" :: ", new Date()); -} - -// Callback function for the connection status -var connectionStatusCallback = (response) => { - if(response.command) { - isDeviceConnected = true; - setTimeout(() => { - getAttributes(); - // getChildDevices(); - // createChildDevice(); - // deleteChildDevice(); - // getTwins(); - }, 10000); - console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + response.uniqueId + "] :: Device Disconnected :: ", new Date()); - } -} - -/* -Type : Callback Function "deviceCallback()" -Usage : Firmware will receive commands from cloud. You can manage your business logic as per received command. -Output : Receive device command, firmware command and other device initialize error response -Input : -*/ -var deviceCallback = function deviceCallback(data){ - console.log("deviceCallback -> data", data) - - if(data) - { - if(data.ct == 0) { - // console.log("\n"+"--- Device Command Received ---"); - var obj = { - "ack": data.ack, - "type": 0, - "msg": "Success", - "cid": data.id ? data.id : null - } - if(data.ack != null) - var bool = 1; // 0 - iotConnectSDK.sendAckCmd(bool, obj) - } - } -} - -/* -Type : Public Method "getAllTwins()" -Usage : To get all the twin properies Desired and Reported -Output : All twin property will receive in above callback function "twinUpdateCallback()" -*/ -// setTimeout(() => { -// iotConnectSDK.getTwins(function (response) { -// console.log("get Twins ==> response ", ); -// }); -// }, 15000); - - -/* -Type : Callback Function "twinUpdateCallback()" -Usage : Manage twin properties as per business logic to update the twin reported property -Output : Receive twin properties Desired, Reported -Input : -*/ -var twinUpdateCallback = function twinUpdateCallback(data){ - // console.log("\n--- Twin desired message received ---"); - // console.log(data); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (key, callbackatt) { - if(key == "$version"){ - callbackatt(); - } else { - var value = data.desired[key]; - if(iotConnectSDK) - { - iotConnectSDK.updateTwin(key,value,(obj)=>{ - console.log(obj); - }) - } else { - console.log("Connection object not founud") - } - callbackatt(); - } - }, function () { }) - } -} - -/* -Type : Public Method "updateTwin()" -Usage : Upate the twin reported property -Output : -Input : "key" and "value" as below - // var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message - // var value = "<< Desired Property value >>"; // Value of respective desired property -*/ -//iotConnectSDK.updateTwin(key,value) - - -/* -Type : Public Method "sendData()" -Usage : To publish the D2C data -Output : -Input : Predefined data object -*/ - - - - -/* -Type : Public Method "dispose()" -Usage : Disconnect the device from cloud -Output : -Input : -Note : It will disconnect the device after defined time -*/ -if(disconnectDuration && disconnectDuration > 0) { - setTimeout(() => { - if(iotConnectSDK && isDeviceConnected == true) - { - iotConnectSDK.dispose() - isDeviceConnected = false; - } else { - console.log("Connection object not founud") - } - }, eval(disconnectDuration * 1000)); -} - -// Callback function for the connection status -var connectionStatusChanged = function connectionStatusChanged(data){ - // console.log("connection status => ", data); - if(data.ct == 3) { - console.log("\n"+"--- Device connection status --- ", data.command); - // console.log(data); - try { - if(data.command) - { - isDeviceConnected = true; - setTimeout(() => { - getAttributes(); - getDevices(); - // iotConnectSDK.getAllTwins(); - // createChildDevice(); - // deleteChildDevice(); - }, 10000); - // console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - // console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - } - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } else { - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Wrong command :: ", new Date()); - } -} - -// Callback function for the Attribute updated -var attributeUpdated = function attributeUpdated(data){ - // console.log("--- Attribute information updated ---", JSON.stringify(data) ); - if(data) - getAttributes(); -} - -var childGlobal = []; -var getAttributes = function getAttributes(){ - console.log('getAttributes') - iotConnectSDK.getAttributes(function(response){ - try { - if(response.data && response.data instanceof Array && response.data.length){ - childGlobal = response.data.map(e => e.device.id); - } - setInterval(() => { - // Non Gateway - var data = [{ - "uniqueId":uniqueId, - "time":new Date(), - "data": { - //"temperature": getRandomValue(1, 50), "latlong1":"["+getRandomValue(-90, 90)+","+getRandomValue(-180, 180)+"]"} // Add your device attributes and respective value here as per standard format defined in sdk documentation - - "temperature":10, - // "long1":31, - // "integer1":55, - // "decimal1":0.555, - - // "time1":"11:55:22", - // "bit1":2, - - // "string1":"red", - - // "gyro": { - // 'bit1':0.1, - - // "decimal1":2.555, - // "integer1":884, - // "latlong1":78945, - // "long1":999, - // "string1":"green", - // "time1":"11:44:22", - // "temperature":200 - // } - } - }] - - // Gateway Device - // var data = [{ - // "uniqueId":uniqueId, - // "time":new Date(), - // "data": {"bit1":1,"Temperature": getRandomValue(1, 50),"gyro":{"x":getRandomValue(1, 50),"y":getRandomValue(1, 50),"z":getRandomValue(1, 50)}} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // },{ - // "uniqueId":"v21tg201c1", //v21tg201c1 , parasewv21c - // "time":new Date(), - // "data": {"bit1":1,"Temperature": getRandomValue(1, 50)} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // }] - // ,{ - // "uniqueId":"parasewv21c1", - // "time":new Date(), - // "data": {"Temperature": getRandomValue(1, 50)} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // }] - - - - - if(iotConnectSDK) - { - console.log('Sensor Data Received ===>>>', JSON.stringify(data,null,2)) - // Device to Cloud data publish - iotConnectSDK.sendData(data) - } else { - console.log("Connection object not founud") - } - }, eval(dataSendInterval * 1000)); - } catch (error) { - console.log("Error while getting attributes :: ",error); - } - }) -} - -console.log("🚀 Nodejs Message format 2.1 SDK") - -var getDevices = function getDevices(){ - iotConnectSDK.getDevices(function(response){ - try { - console.log("response.data Devices ", JSON.stringify(response)); - // SendData(response.data); - } catch (error) { - console.log("Error while getting attributes :: ",error); - } - }) -} - -// Callback function for the device updated -var deviceUpdated = function deviceUpdated(data){ - console.log("Device Updated => ", data); -} - -// Callback function to receive OTA command -var receiveOTA = function receiveOTA(data){ - // console.log("Receive OTA => ", JSON.stringify(data)); - if(data && data.ct == 1) { - var obj = { - "ack": data.ack, - "type": data.ct, - // "st": 7, - "msg": "Success", - "cid": "" // For gatewat device only for child device - } - // var msgType = 6; - if(data.ack != null) - { - var bool = 2; - iotConnectSDK.sendAckOTA(bool, obj) - } - } else { - console.log("Wrong command ") - } -} - -// Callback function to receive the module information -var moduleReceived = function moduleReceived(data){ - console.log("module received => ", data); - if(data && data.ct == 1) { - var obj = { - "ack": data.ack, - "type": data.ct, - "msg": "Success", - "cid": "" // For gatewat device only for child device - } - // var msgType = 6; - if(data.ack != null) - { - var bool = 1; - iotConnectSDK.sendAckModule(bool, obj) - } - } else { - console.log("Wrong command ") - } -} - -var initCallbacks = function initCallbacks(){ - if(iotConnectSDK){ - iotConnectSDK.setConnectionStatusChangedCallback(connectionStatusChanged); - iotConnectSDK.setTwinChangedCallback(twinUpdateCallback); - iotConnectSDK.setDeviceCommandCallback(deviceCallback); - iotConnectSDK.setOTAReceivedCallback(receiveOTA); - // iotConnectSDK.setAttributeChangedCallback(attributeUpdated); - iotConnectSDK.setDeviceChangedCallback(deviceUpdated); - iotConnectSDK.setModuleReceivedCallback(moduleReceived); - } - // For 2.1 - // iotConnectSDK.getCreateChildDeviceCallback(createDeviceCallback); - // iotConnectSDK.getDeleteChildDeviceCallback(deleteDeviceCallback); -} - -// New Methods -var createChildDevice = function createChildDevice(){ - var deviceId = "ac001"; - var deviceTag = "child12"; - var displayName = "AC badroom"; - iotConnectSDK.createChildDevice(deviceId, deviceTag, displayName, function(response){ - try { - console.log("Create child device request :: ", response); - } catch (error) { - console.log("Error while create child device :: ",error.message); - } - }) -} - -var deleteChildDevice = function deleteChildDevice(){ - var deviceId = "ac00111"; - iotConnectSDK.deleteChildDevice(deviceId, function(response){ - try { - console.log("Delete child device request :: ", response); - } catch (error) { - console.log("Error while delete child device :: ",error.message); - } - }) -} - -/* -Type : Function "getRandomValue()" -Usage : To generate the random value for simulated data -Input : It will gives random number between min and max range. -Output : Random number -x`*/ -function getRandomValue(min, max) { - return (Math.random() * (max - min) + min).toFixed(0); -} \ No newline at end of file diff --git a/sample/tpm/example.js b/sample/tpm/example.js deleted file mode 100644 index 7c5ca7f..0000000 --- a/sample/tpm/example.js +++ /dev/null @@ -1,426 +0,0 @@ -'use strict'; - -var SDKClient = require('iotconnect-sdk'); -// var tpmSecurity = require('azure-iot-security-tpm'); -// var tssJs = require("tss.js"); - -var iotConnectSDK = ""; - -// console.log(SDKClient); -// return false; -var readline = require('readline'); -var async = require('async'); -var fs = require('fs-extra'); -// const { try } = require('bluebird'); -var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); -var env = process.argv[2]; -var sdkOptions = { - "debug" : true, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimted - "fileCount": 5 // Default value = 1 - }, - "isSimulatedTPMDevice": true, - "devicePrefix": false, - "azureIotEdgeDevice": false -} -var isDeviceConnected = false; - -const dpsConnectionString = "<>"; - -const endorcementKey = "<>"; - -var deviceId = "AAA27"; -var sId = "ZjlkYTY5MWU3NDc5NGRiNWE2NmZkYTVmNzAxOTIzNjI=UTE6MDQ6MDMuMDA="; -var deviceScopeId = "0ne000F7F02"; - -async.series([ - function(cb_series) { - rl.question('Enter device serial number : ', function (uniqueId) { - uniqueId = deviceId; - rl.question('Enter SID : ', function (id) { - sId = id ? id : sId; - rl.question('Enter scopeId : ', function (scopeId) { - scopeId = deviceScopeId; - if(!isDeviceConnected) { - // iotConnectSDK = new SDKClient(cpId, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); - iotConnectSDK = new SDKClient(uniqueId, sId, scopeId, sdkOptions, getSecretCallback, function(response){ - if(response.status){ - // iotConnectSDK.connect(); - setTimeout(() => { - // console.log("==================================== connect ") - initCallbacks(); - - setTimeout(() => { - iotConnectSDK.connect(); - }, 1000); - - }, 5000); - } else { - console.log("DeviceId :: SDK initialization failed :: ", new Date()); - } - }); - } else { - console.log("Device is already connected"); - } - }); - }); - }); - } -], function(err, response) { }) - -var getSecretCallback = function getSecretCallback(key) { - switch (key) { - case "DPSCS": //DPS connection string - return dpsConnectionString; - break; - - case "EKEY": //DPS connection string - return endorcementKey; - break; - - case "IOTHUB": //IoTHub Host name - return "iothub"; - break; - - default: - break; - } -} - -var getAttributest = function getAttributest(){ - iotConnectSDK.getAttributes(function(response){ - try { - console.log("response.data ==>", JSON.stringify(response.data)); - SendData(response.data); - } catch (error) { - console.log("Error while getting attributes :: ",error); - } - }) -} - -var deviceCallback = function deviceCallback(data){ - - if(data != null && data != undefined && data.ack != undefined && data.cmdType != null) - { - if(data.cmdType == '0x01') { - console.log("\n"+"--- Device Command Received ---"); - console.log(data); - var obj = { - "ackId": data.ackId, - "st": 6, - "msg": "", - "childId": "" - } - var msgType = 5; - if(data.ackId != null) - iotConnectSDK.sendAck(obj, msgType) - } else if(data.cmdType == '0x02') { - console.log("\n"+"--- OTA Command Received ---"); - console.log(data); - if(data.urls) { - async.forEachSeries(data.urls, function (cmddetail, cbota) { - if("uniqueId" in cmddetail) { - var childId = cmddetail.uniqueId; - } else { - var childId = null; - } - var obj = { - "ackId": data.ackId, - "st": 7, - "msg": "", - "childId": childId - } - var msgType = 11; - if(data.ackId != null) - { - /* - Type : Public Method "sendAck()" - Usage : Send firmware command received acknowledgement to cloud - - status Type - st = 7; // firmware - - Message Type - msgType = 11; // for "0x02" Firmware command - */ - console.log("obj => ", obj); - iotConnectSDK.sendAck(obj, msgType) - } - cbota(); - }, function () { }); - } - } else if(data.cmdType == '0x16') { - // console.log("\n"+"--- Device connection status ---"); - // console.log(data); - // try{ - - // iotConnectSDK.getAllTwins(); - // } catch(e) { - // console.log(e) - // } - // setTimeout(() => { - // // getAttributest(); - // console.log("hello get all twins"); - // }, 10000); - try { - if(data.command) - { - isDeviceConnected = true; - getAttributest(); - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - } - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } - } -} - -var twinUpdateCallback = function twinUpdateCallback(data){ - console.log("\n"+"--- Twin desired message received ---"); - console.log(data); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (key, callbackatt) { - if(key == "$version"){ - callbackatt(); - } else { - var value = data.desired[key]; - iotConnectSDK.updateTwin(key, value) - callbackatt(); - } - }, function () { }) - } -} - -var setReadline = function setReadline (attr, type, callback){ - if(type == 1) - var space = " "; - else - var space = ""; - rl.question(space+'Enter '+attr+' : ', function (value) { - var obj = {}; - obj[attr] = value; - callback(obj); - }); -} - -var callAgain = function callAgain (){ - rl.question('\nWould you like to send data again ? (Y/N) : ', function (status) { - if(status == "Y" || status == "y") - { - try { - getAttributest(); - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } - else - process.exit(); - }); -} - -var SendData = function SendData(sensordata){ - var sendTeledataData = []; - var cnt = 0; - var text = ""; - var tagArray = []; - if(sensordata.length > 0) { - async.forEachSeries(sensordata, function(inputdata, data_cb) { - if(cnt == 0 && inputdata.device.tg) { - console.log("Note :: It includes the single device from each tag."); - text = "(Gateway Device) "; - } else { - text = ""; - } - if(inputdata['attributes'].length > 0) - { - cnt++; - if (tagArray.indexOf(inputdata.device.tg) == -1) { - // tagArray.push(inputdata.device.tg); - if(inputdata.device.tg) - console.log("\n## TAG :: "+inputdata.device.tg+" [Device "+text+":: "+inputdata.device.id+"]"); - else - console.log("\n## Device "+text+":: "+inputdata.device.id); - var sendordataObj = { - "uniqueId": inputdata.device.id, - "time" : new Date(), - "data": {} - } - async.forEachSeries(inputdata.attributes, function(attr, attrdata_cb) { - if(attr.d) - { - console.log("Enter "+attr.ln+" : "); - sendordataObj.data[attr.ln] = {}; - async.forEachSeries(attr.d, function(attrChild, attrdataChild_cb) { - setReadline(attr.ln+'.'+attrChild.ln, 1, function(resultdata){ - sendordataObj.data[attr.ln][attrChild.ln] = resultdata[attr.ln+'.'+attrChild.ln]; - attrdataChild_cb() - }); - },function(){ - attrdata_cb() - }); - } - else - { - setReadline(attr.ln, 0, function(resultdata){ - sendordataObj.data[attr.ln] = resultdata[attr.ln]; - attrdata_cb(); - }); - } - },function(){ - sendTeledataData.push(sendordataObj); - data_cb(); - }); - } else { - data_cb(); - } - } - },function(){ - var data = sendTeledataData; - iotConnectSDK.sendData(data); - setTimeout(function() { - callAgain(); - }, 500); - }); - } else { - console.log("No Attribute data found."); - } -} - -function disconnectDevice(){ - if(isDeviceConnected) { - iotConnectSDK.disconnect(); - } else { - console.log("Device is already disconnected"); - } -} - - -// Callback function for the connection status -var connectionStatusChanged = function connectionStatusChanged(data){ - // console.log("connection status => ", data); - if(data.cmdType == '0x16') { - console.log("\n"+"--- Device connection status ---"); - console.log(data); - try { - if(data.command) - { - isDeviceConnected = true; - setTimeout(() => { - // getAttributest(); - iotConnectSDK.getAllTwins(); - }, 10000); - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - } - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } else { - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Wrong command :: ", new Date()); - } -} - -// Callback function for the Attribute updated -var attributeUpdated = function attributeUpdated(data){ - // console.log("--- Attribute information updated ---", data); - if(data) - getAttributest(); -} - -// Callback function for the device updated -var deviceUpdated = function deviceUpdated(data){ - console.log("Device Updated => ", data); -} - -// Callback function to receive OTA command -var receiveOTA = function receiveOTA(data){ - // console.log("Receive OTA => ", data); - if(data.cmdType == '0x02') { - console.log("\n"+"--- OTA Command Received ---"); - console.log(data); - if(data.urls) { - async.forEachSeries(data.urls, function (cmddetail, cbota) { - if("uniqueId" in cmddetail) { - var childId = cmddetail.uniqueId; - } else { - var childId = null; - } - var obj = { - "ackId": data.ackId, - "st": 7, - "msg": "", - "childId": childId - } - var msgType = 11; - if(data.ackId != null) - { - /* - Type : Public Method "sendAck()" - Usage : Send firmware command received acknowledgement to cloud - - status Type - st = 7; // firmware - - Message Type - msgType = 11; // for "0x02" Firmware command - */ - iotConnectSDK.sendAck(obj, msgType) - } - cbota(); - }, function () { }); - } - } -} - -// Callback function to receive the module information -var moduleRecieved = function moduleRecieved(data){ - console.log("module received => ", data); -} - -// Callback function to request for the secret configurations -// var requestForSecet = function requestForSecet(key, callback){ -// switch (key) { -// case "DPSCS": //DPS connection string -// callback(true, dpsConnectionString) -// break; - -// case "EKEY": //Endorcement key -// try { -// callback(true, endorcementKey); -// } catch (error) { -// callback(false, null); -// console.log("error => ", error); -// } -// break; - -// case "IOTHUB": //IoTHub host name -// return "" -// break; - -// default: -// break; -// } -// } - -var initCallbacks = function initCallbacks(){ - // console.log("iotConnectSDK => ", iotConnectSDK); - iotConnectSDK.setConnectionStatusChangedCallback(connectionStatusChanged) - iotConnectSDK.setTwinChangedCallback(twinUpdateCallback) - iotConnectSDK.setDeviceCommandCallback(deviceCallback) - iotConnectSDK.setOTAReceivedCallback(receiveOTA) - iotConnectSDK.setAttributeChangedCallback(attributeUpdated) - iotConnectSDK.setDeviceChangedCallback(deviceUpdated) - iotConnectSDK.setModuleRecievedCallback(moduleRecieved) - // iotConnectSDK.getSecrets(requestForSecet) -} - -// setTimeout(() => { -// disconnectDevice(); -// }, 30000); \ No newline at end of file diff --git a/sample/tpm/firmware.js b/sample/tpm/firmware.js deleted file mode 100644 index 07f20a7..0000000 --- a/sample/tpm/firmware.js +++ /dev/null @@ -1,259 +0,0 @@ -'use strict'; - -/* -Hope you have installed the node SDK as guided on SDK documentation. -*/ -var SDKClient = require('iotconnect-sdk'); -var async = require('async'); - -/* -## Prerequisite parameter to run this sampel code -- cpId :: It need to get from the IoTConnect platform "Settings->Key Vault". -- uniqueId :: Its device ID which register on IotConnect platform and also its status has Active and Acquired -- env :: It need to get from the IoTConnect platform "Settings->Key Vault". -- dataSendInterval :: send data frequency in seconds -- disconnectDuration:: Device connection close after defined time in seconds to call dispose() method. Keep "0" if don't need disconnect the device. -- sdkOptions :: It helps to define the path of self signed and CA signed certificate as well as define the offlinne storagr params -*/ -var cpId = "<< CPID >>"; -var uniqueId = "<< Device UniqueID >>"; -var env = "<< Environment >>"; //Environment DEV, QA, POC, AVNET, PROD - (Default - PROD) -var dataSendInterval = 10; // send data frequency in seconds -var disconnectDuration = 0; //Seconds // Keep "0" If no need to disconnect -var isDeviceConnected = false; - -/* -Note: sdkOptions is optional. Mandatory for "certificate" X.509 device authentication type and discoveryUrl. - "certificate": //For SSL CA signed and SelfSigned authorized device only otherwise skip this property - - SSLKeyPath: your device key - - SSLCertPath: your device certificate - - SSLCaPath : Root CA certificate - "offlineStorage": It helps, store the data in log file which will be created beside the firmware sample file. So, make sure your root directory has proper permission to create the log files and folder. It will store offline data once device lost the network connection. - - disabled : false = offline data storing, true = not storing offline data (Default = false) - - availSpaceInMb : Define the file size of offline data which should be in (MB) (Default = unlimited) - - fileCount : Number of file need to create for offline data (Default = 1) - - Note : It will create 5 files of 2 MB. - Define setting or leave it blank. It will set the default setting for offline storage configuration as per defined below. It may harm your device by storing the large data. Once memory get full may chance to your device script crash and stop the execution. -*/ - -var sdkOptions = { - "certificate": { - "SSLKeyPath" : "<< Certificate file path >>", - "SSLCertPath" : "<< Certificate file path >>", - "SSLCaPath" : "<< Certificate file path >>" - }, - "offlineStorage": { - "disabled": false, //default value = false, false = store data, true = not store data - "availSpaceInMb": 1, //in MB Default value = unlimted - "fileCount": 5 // Default value = 1 - } -} - -/* -Type : Object Initialization "new SDKClient()" -Usage : To Initialize SDK and Device cinnection -Output : Callback methods for command and twin properties -Input : cpId, uniqueId, sdkOptions, env as explained above and deviceCallback and twinUpdateCallback is callback functions -*/ -var iotConnectSDK = ""; -setTimeout(() => { - if(!isDeviceConnected) { - iotConnectSDK = new SDKClient(cpId, uniqueId, deviceCallback, twinUpdateCallback, sdkOptions, env); - } else { - console.log("Device is already connected"); - } -}, 1000); - - -/* -Type : Callback Function "deviceCallback()" -Usage : Firmware will receive commands from cloud. You can manage your business logic as per received command. -Output : Receive device command, firmware command and other device initialize error response -Input : -*/ -var deviceCallback = function deviceCallback(data){ - if(data != null && data != undefined && data.ack != undefined && data.cmdType != null) - { - if(data.cmdType == '0x01') { - console.log("\n"+"--- Device Command Received ---"); - console.log(data); - var obj = { - "ackId": data.ackId, - "st": 6, - "msg": "", - "childId": "" - } - var msgType = 5; - if(data.ackId != null) - { - /* - Type : Public Method "sendAck()" - Usage : Send device command received acknowledgment to cloud - - status Type - st = 6; // Device command Ack status OR - st = 4; // Failed Ack - - Message Type - msgType = 5; // for "0x01" device command - */ - if(iotConnectSDK) - { - iotConnectSDK.sendAck(obj, msgType) - } else { - console.log("Connection object not founud") - } - } - } else if(data.cmdType == '0x02') { - console.log("\n"+"--- Firmware OTA Command Received ---"); - console.log(data); - async.forEachSeries(data.urls, function (cmddetail, cbota) { - if("uniqueId" in cmddetail) { - var childId = cmddetail.uniqueId; - } else { - var childId = null; - } - var obj = { - "ackId": data.ackId, - "st": 7, - "msg": "", - "childId": childId - } - var msgType = 11; - if(data.ackId != null) - { - /* - Type : Public Method "sendAck()" - Usage : Send firmware command received acknowledgement to cloud - - status Type - st = 7; // firmware OTA command Ack status OR - st = 4; // Failed Ack - - Message Type - msgType = 11; // for "0x02" Firmware command - */ - if(iotConnectSDK) - { - iotConnectSDK.sendAck(obj, msgType) - } else { - console.log("Connection object not founud") - } - } - cbota(); - }, function () { }); - } else if(data.cmdType == '0x16') { - console.log("\n"+"--- Device connection status ---"); - console.log(data); - try { - if(data.command) - { - isDeviceConnected = true; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Connected :: ", new Date()); - } else { - isDeviceConnected = false; - console.log("\nDeviceId ::: [" + data.uniqueId + "] :: Device Disconnected :: ", new Date()); - } - } catch (error) { - console.log("Error while getting attributes :: ",error.message); - } - } - } -} - -/* -Type : Public Method "getAllTwins()" -Usage : To get all the twin properies Desired and Reported -Output : All twin property will receive in above callback function "twinUpdateCallback()" -*/ -// iotConnectSDK.getAllTwins(); - - -/* -Type : Callback Function "twinUpdateCallback()" -Usage : Manage twin properties as per business logic to update the twin reported property -Output : Receive twin properties Desired, Reported -Input : -*/ -var twinUpdateCallback = function twinUpdateCallback(data){ - // console.log("\n--- Twin desired message received ---"); - // console.log(data); - if(data.desired) { - async.forEachSeries(Object.keys(data.desired) , function (key, callbackatt) { - if(key == "$version"){ - callbackatt(); - } else { - var value = data.desired[key]; - if(iotConnectSDK) - { - iotConnectSDK.updateTwin(key,value) - } else { - console.log("Connection object not founud") - } - callbackatt(); - } - }, function () { }) - } -} - -/* -Type : Public Method "updateTwin()" -Usage : Upate the twin reported property -Output : -Input : "key" and "value" as below - // var key = "<< Desired property key >>"; // Desired proeprty key received from Twin callback message - // var value = "<< Desired Property value >>"; // Value of respective desired property -*/ -//iotConnectSDK.updateTwin(key,value) - - -/* -Type : Public Method "sendData()" -Usage : To publish the D2C data -Output : -Input : Predefined data object -*/ -setInterval(() => { - // Non Gateway - var data = [{ - "uniqueId":uniqueId, - "time":new Date(), - "data": {} // Add your device attributes and respective value here as per standard format defined in sdk documentation - }] - - // Gateway Device - // var data = [{ - // "uniqueId":uniqueId, - // "time":new Date(), - // "data": {} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // },{ - // "uniqueId":uniqueId, - // "time":new Date(), - // "data": {} // Add your device attributes and respective value here as per standard format defined in sdk documentation - // },] - - if(iotConnectSDK) - { - // Device to Cloud data publish - iotConnectSDK.sendData(data) - } else { - console.log("Connection object not founud") - } -}, eval(dataSendInterval * 1000)); - - -/* -Type : Public Method "dispose()" -Usage : Disconnect the device from cloud -Output : -Input : -Note : It will disconnect the device after defined time -*/ -if(disconnectDuration && disconnectDuration > 0) { - setTimeout(() => { - if(iotConnectSDK && isDeviceConnected == true) - { - iotConnectSDK.dispose() - isDeviceConnected = false; - } else { - console.log("Connection object not founud") - } - }, eval(disconnectDuration * 1000)); -} \ No newline at end of file diff --git a/sample/tpm/generateEndorcementKey.js b/sample/tpm/generateEndorcementKey.js deleted file mode 100644 index 046b3aa..0000000 --- a/sample/tpm/generateEndorcementKey.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var tpmSecurity = require('azure-iot-security-tpm'); -var tssJs = require("tss.js"); -var readline = require('readline'); -var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -try { - rl.question('Enter device registration ID : ', function (regstrationId) { - var myTpm = new tpmSecurity.TpmSecurityClient(regstrationId, new tssJs.Tpm(true)); - myTpm.getEndorsementKey(function(err, endorsementKey) { - if (err) { - console.log('The error returned from get key is: ' + err); - process.exit(); - } else { - console.log('the endorsement key is: ' + endorsementKey.toString('base64')); - process.exit(); - } - }); - }); -} catch (error) { - console.log("Error : ", error.message); -} - - -//https://docs.microsoft.com/en-us/azure/iot-dps/quick-create-simulated-device-tpm-node \ No newline at end of file