NodeJS

NodeJS

Card Image

Version 1.0

Updated on 15 January 2024

This /IOTCONNECT™ NodeJS SDK package will show you how to install and run
the firmware file.

Date Name Download
15 January 2024 NodeJS SDK V1.0 Download

Getting started

Prerequisites

Before you install and run the firmware file, we recommend to check with
the following setup requirements:

  •  NodeJs : Node.js supported version v8.x and above
  •  Npm : NPM is compatible with the node version

Installation

  • you can clone the full sample source code from this repository given
    at the Download link.
  • Or run the “git clone –branch master-std-21 https://github.com/avnet-iotconnect/iotc-node-sdk.git” at the terminal/command prompt to get the full SDK file.
  • To install the required libraries use the below command:
    – Goto SDK “iotc-node-sdk” directory path using terminal/Command
    prompt
    – cd iotc-node-sdk
    – npm install (Install prerequisite nodejs library)
    – npm install iotconnect-sdk (Install the ‘iotconnect-sdk’ package
    in nodejs library)
  • Using terminal/command prompt goto sample folder
    – cd sample
  • 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.

Run

       – node firmware.js (This script send the data on the cloud as per
configured device detail)

       – node example.js *<<env>>* (Command line
experience to test the sdk)

Explanation

To initialize the SDK object, you need to import the below SDK package

var SDKClient = require('iotconnect-sdk');

Prerequisite configuration

string cpId = "<Your cpId>";
   string uniqueId = "<Your UniqueID>";
   string env = "<your env>";
   string sId = "<Your SID>";
   string platform = "<Your platform>"
  • cpId : It need to get from the /IOTCONNECT™ platform
    “Settings->Key Vault”.
  • uniqueId : Your device uniqueId
  • env : It need to get from the /IOTCONNECT™ platform
    “Settings->Key Vault”.
  • SId : It is the company code. You can get it from the
    /IOTCONNECT™ UI portal “Settings -> Key Vault -> SDK Identities
    -> select language DotNet and Version 1.0”
  • platform : It is either aws or az

Notes: Set either SID or CPID, As any one of it will be optional.

SdkOptions

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
      "SSLKeyPath"	: "<< SystemPath >>/device.key",
      "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
      // "debug" : true, // Private setting, false(default) = Don't show log, true = Show log
      
      "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": ""
      },
      "cpId" : cpId,
      "env" : env,
      "pf": pf
  } 
    

Notes:

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 a mandatory parameter to get device details.
  - discoveryUrl : “Your Discovery Url”

DevicePrimarykey

It is mandatory for the Symmetric Key Authentication support. You can
get it from the /IOTCONNECT™ UI portal “Device -> Select device ->
info(Tab) -> Connection Info -> Device Connection”
  - devicePrimaryKey : “<DevicePrimaryKey>”

 

Notes: sdkOptions is optional but mandatory for SSL/x509 device
authentication type only. Define proper setting or leave it NULL. If
you do not provide offline storage, it will set the default settings
as per defined above. It may harm your device by storing the large
data. Once memory gets full may chance to stop the execution. To
initialize the SDK object and connect to the cloud

 

To Initialize the SDK object and connect to the cloud

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 /IOTCONNECT™SDK had initialized
  initCallbacks();
    

To receive the command from Cloud to Device(C2D)

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 OTA Command from Cloud to Device(C2D)

// 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 Shadow from Cloud to Device(C2D)

var twinUpdateCallback = function twinUpdateCallback(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 Shadow Property Device to Cloud(D2C)

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 request the list of attribute with the respective device type

iotConnectSDK.getAttributes(function(response){
    console.log("Attributed :: "+ response);
  });
This is the standard data input format for Gateway and non Gateway device to
send the data on /IOTCONNECT™ cloud(D2C).

1. For Non Gateway Device 
    String deviceData = "[{
      'uniqueId': '<< Device UniqueId >>',
      'time' : '<< date >>',
      'data': {}
    }]";
    
    2. For Gateway and multiple child device 
    String deviceData = "[{
      'uniqueId': '<< Gateway Device UniqueId >>', // It should be must first object of the array
      'time': '<< date >>',
      'data': {}
    },
    {
      'uniqueId':'<< Child DeviceId >>', //Child device
      'time': '<< date >>',
      'data': {}
    }]";
    
    sdkClient.SendData(deviceData);

Notes: Date time will be in ISO 8601 format as
“YYYY-MM-DDTHH:MM:SS.sssZ”. Example: “2019-12-24T10:06:17.857Z”

“time” : Date format should be as defined //”2021-01-24T10:06:17.857Z”
“data” : JSON data type format // {“temperature”: 15.55, “gyroscope” : {
‘x’ : -1.2 }}

To send the command acknowledgment

var command = JsonConvert.DeserializeObject<DeviceCommand>(arg);
    client.SendAckCmd(command.Ack.Value, 6, "Ack done.!!!");
    
    "ackId(*)" 	: Command Acknowledgment GUID which will receive from command payload (data.ackId)
    "st(*)"		: Acknowledgment status sent to cloud (4 = Fail, 6 = Device command[0x01], 7 = Firmware OTA command[0x02])
    "msg" 		: It is used to send your custom message
    "childId" 	: It is used for Gateway's child device OTA update only
            0x01 : null or "" for Device command
              0x02 : null or "" for Gateway device and mandatory for Gateway child device's OTA update.
               How to get the "childId" .?
               - You will get child uniqueId for child device OTA command from payload "data.urls[~].uniqueId"
    "msgType" 	: Message type (5 = "0x01" device command, 11 = "0x02" Firmware OTA command)
    Note : (*) indicates the mandatory element of the object.
    

To disconnect the device from the cloud

sdkClient.Dispose();
    

To get the shadow property Desired and Reported

sdkClient.GetShadows();
    

To get the all attributes

sdkClient.GetAttributes();