All Products
Search
Document Center

:SDK for Node.js

Last Updated:May 13, 2024

You can develop a driver by using the SDK for Node.js to connect a device to a gateway. Then connect the device to the IoT Platform.

For the source code of the SDK for Node.js, visit Open-source SDK for Node.js.

Installation and usage

  1. Run the following command to install the SDK:
    npm install linkedge-thing-access-sdk
  2. After the SDK is installed, you can develop drivers based on the SDK interface.
    Important If you run a driver directly after the driver development is completed, an error will occur. You must deploy the driver to the gateway on the IoT Platform console before you run the driver. For more information about how to deploy the driver to the gateway, see Driver Development.

    The following is an example of how to use the SDK to develop a driver:

    const {
      Config,
      ThingAccessClient
    } = require('linkedge-thing-access-sdk');
    
    const callbacks = {
      setProperties: function (properties) {
        // Set properties to the physical thing and return the result.
        // Return an object representing the result or the promise wrapper of the object.
        return {
          code: 0,
          message: 'success',
        };
      },
      getProperties: function (keys) {
        // Get properties from the physical thing and return the result.
        // Return an object representing the result or the promise wrapper of the object.
        return {
          code: 0,
          message: 'success',
          params: {
            key1: 'value1',
            key2: 'value2',
          }
        };
      },
      callService: function (name, args) {
        // Call services on the physical thing and return the result.
        // Return an object representing the result or the promise wrapper of the object.
        return new Promise((resolve) => {
          resolve({
            code: 0,
            message: 'success',
          });
        });
      }
    };
    Config.get()
      .then(config => {
        const thingInfos = config.getThingInfos();
        thingInfos.forEach(thingInfo => {
          const client = new ThingAccessClient(thingInfo, callbacks);
          client.registerAndOnline()
            .then(() => {
              return new Promise(() => {
                setInterval(() => {
                  client.reportEvent('high_temperature', { temperature: 41 });
                  client.reportProperties({ 'temperature': 41 });
                }, 2000);
              });
            })
            .catch(err => {
              console.log(err);
              client.cleanup();
            });
            .catch(err => {
              console.log(err);
            });
        });
      });

Constants

ParameterTypeDescription
PRODUCT_KEYStringA key in the configuration object. The key is passed to the ThingAccessClient constructor. Set the value to the ProductKey that was allocated to you by IoT Platform.
DEVICE_NAMEStringA key in the configuration object. The key is passed to the ThingAccessClient constructor. Set the value to the DeviceName that was allocated to you by IoT Platform.
LOCAL_NAMEStringA key in the configuration object. The key is passed to the ThingAccessClient constructor. Set the value to the on-premises device name.
CALL_SERVICEStringA key in the callback object. The key is passed to the ThingAccessClient constructor. Set the value to the callback function that is used to call device services. For more information about the function definition, see callbacks.callService().
GET_PROPERTIESStringA key in the callback object. The key is passed to the ThingAccessClient constructor. Set the value to the callback function that is used to obtain device properties. For more information about the function definition, see callbacks.getProperties().
SET_PROPERTIESStringA key in the callback object. The key is passed to the ThingAccessClient constructor. Set the value to the callback function that is used to set device properties. For more information about the function definition, see callbacks.setProperties().
RESULT_SUCCESSNumberThe operation was successful. It is a status code used by the callback functions.
RESULT_FAILURENumberThe operation failed. It is a status code used by the callback functions.
ERROR_CLEANUPStringThe error code for the cleanup() function.
ERROR_CONNECTStringThe error code for the registerAndOnline() function.
ERROR_DISCONNECTStringThe error code for the offline() function.
ERROR_GET_CONFIGStringThe error code for the getConfig() function.
ERROR_GET_TSLStringThe error code for the getTsl() function.
ERROR_GET_TSL_EXT_INFOStringThe error code for the getTslExtInfo() function.
ERROR_UNREGISTERStringThe error code for the unregister() function.

Config

The information related to driver configurations.

  • static get()

    Returns the global driver configuration object, which is generated by the system when the device is associated with the driver.

    Note The difference between the Config.get() function and the getConfig() function is that getConfig() returns a configuration string whereas Config.get() returns a configuration object.
    Response:
    Promise<Config>
  • static registerChangedCallback(callback)

    The callback function that is used to make configuration changes

    Table 1. Request parameters
    ParameterTypeDescription
    callbackFunctionThe callback function that is called when a configuration change occurs.
  • static unregisterChangedCallback(callback)

    The callback function that is used to revert configuration changes.

    Table 2. Request parameters
    ParameterTypeDescription
    callbackFunctionThe callback function that is called when a configuration change occurs.
  • Config(string)

    Constructs a new Config object based on a configuration string.

    Table 3. Request parameters
    ParameterTypeDescription
    stringStringThe JSON configuration string.
  • getThingInfos()

    Returns all device-related information.

    Response:
    ThingInfo[]
  • getDriverInfo()

    Returns the driver information.

    Response:
    Object

ThingInfo

This function can be used to identify the information of devices that are connected to Link IoT Edge. After a device is connected to Link IoT Edge, information such as the ProductKey, DeviceName, and custom configurations of the device can be identified by the function.

ThingInfo(productKey, deviceName, custom)

Constructs a new ThingInfo object.

Table 4. Request parameters
ParameterTypeDescription
productKeyStringThe unique identifier of the product.
deviceNameStringThe name of the device.
customObjectCustom device configurations.

ThingAccessClient

The client that allows devices to connect to IoT Platform. You can use the client to report properties and events. You can also use the client to send commands from the cloud to the devices.

  • ThingAccessClient(config, callbacks)

    The constructor, which is initialized by specifying the config and callbacks parameters.

    Table 5. Request parameters
    ParameterTypeDescription
    configObjectThe metadata that is used to configure the client. Format:
    {
        "productKey": "Your Product Key", 
        "deviceName": "Your Device Name"
    }
    callbacksObjectThe callback function object. Format:
    callbacks: {
        setProperties: function(properties) {},
        getProperties: function(keys) {},
        callService: function(name, args) {}
    }
    • For callback parameters of setting device properties, see the callbacks.setProperties section.
    • For callback parameters of obtaining device properties, see the callbacks.getProperties section.
    • For callback parameters of calling device services, see the callbacks.callService section.
  • callbacks.setProperties(properties)

    The callback function that is used to set device properties. You can use the callback function to set device properties.

    Table 6. Request parameters
    ParameterTypeDescription
    propertiesObjectThe property object. The format of the property value is as follows:
    {
        "key1": "value1", 
        "key2": "value2"
    }
    Response:
    {
      "code": 0,
      "message": "string",
      "params": {}
    }
    Table 7. Response Parameters
    ParameterTypeDescription
    codeNumberThe status code.
    • 0: indicates that the call was successful.
    • Non-zero: indicates that the call failed and an error corresponding to the non-zero value was returned.
    messageStringOptional. The status description information.
    paramsObjectOptional. This parameter can be used to return the configuration result of each property. The parameter contains the actual values of the properties.
  • callbacks.getProperties(keys)

    The callback function that is used to obtain specified device properties. You can use the callback function to obtain the properties of the device.

    Table 8. Request parameters
    ParameterTypeDescription
    keysString[]The names of the properties. The format is as follows:
    ['key1', 'key2']
    Response:
    {
      "code": 0,
      "message": "string",
      "params": {}
    }
    Table 9. Response Parameters
    ParameterTypeDescription
    codeNumberThe status code.
    • 0: indicates that the call was successful.
    • Non-zero: indicates that the call failed and an error corresponding to the non-zero value was returned.
    messageStringOptional. The status description information.
    paramsObjectOptional. This parameter can be used to return the value of the specified properties if the request is successful.
  • callbacks.callService(name, args)

    The callback function that is used to call device services. You can use a callback function to call the device service.

    Table 10. Request parameters
    ParameterTypeDescription
    nameStringThe name of the device service.
    argsObjectThe list of service input parameters. The format is as follows:
    {
        "key1": "value1", 
        "key2": "value2"
    }
    Table 11. Response Parameters
    ParameterTypeDescription
    codeNumberThe status code.
    • 0: indicates that the call was successful.
    • Non-zero: indicates that the call failed and an error corresponding to the non-zero value was returned.
    messageStringOptional. The status description information.
    paramsObjectOptional. This parameter can be used to return additional information when the service is called.
  • registerAndOnline()

    Registers the device on the gateway and notifies the gateway to connect the device to IoT Platform. You must register and connect the devices to IoT platform before they can receive commands from or send data to IoT platform.

    Response:
    Promise<Void>
  • online()

    Notifies the gateway that the device is online. The function is used when the device is offline and then is online again.

    Response:
    Promise<Void>
  • offline()

    Notifies the gateway that the device is offline.

    Response:
    Promise<Void>
  • reportEvent(eventName, args)

    Reports device events to IoT Platform.

    Table 12. Request parameters
    ParameterTypeDescription
    eventNameStringThe event name, which is the same as the name of the event you specified in the product definition.
    argsObjectThe keys and values in the event. The format is as follows:
    {
        "key1": "value1", 
        "key2": "value2"
    }
  • reportProperties(properties)

    Reports device properties to IoT Platform.

    Table 13. Request parameters
    ParameterTypeDescription
    propertiesObjectThe keys and values in the properties. The format is as follows:
    {
        "key1": "value1", 
        "key2": "value2"
    }
  • getTsl()

    Returns the TSL string of the device. The data format is the same as in IoT Platform.

    Response:
    Promise<Void>
  • getTslExtInfo()

    Returns the extended information of the TSL.

    Response:
    Promise<String>
  • cleanup()

    Recycles resources. You can use this function to free up resources.

    Response:
    Promise<Void>
  • unregister()

    Removes a device from the gateway. Use this function with caution.

    Response:
    Promise<Void>

getConfig()

Obtains the driver configuration string. which is generated by the system when the device is associated with the driver.
Note The difference between the static get() function (Config.get()) is that getConfig() returns a configuration string whereas Config.get() returns a configuration object.
Response:
Promise<String>

destroy()

Destroys all resources used by the SDK. You can call the destroy() function when you no longer want to use the SDK.

Response:
Promise<Void>