Node.js SDK

Updated at:

You can use the device access software development kit (SDK) to develop drivers on a gateway. These drivers connect devices to the gateway, which in turn connects them to IoT Platform.

For the open source code of the Node.js SDK, see the open source Node.js library.

Installation and usage

  1. Install the SDK.
    npm install linkedge-thing-access-sdk
  2. After the installation is complete, you can use the SDK interfaces to develop the driver.
    Important If you run the driver directly after development, an error occurs. You must deploy the driver to the gateway from the IoT Platform console. For more information about how to deploy a driver to a gateway, see Driver development.

    The following code snippet shows an example of how to develop a driver using the SDK.

    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);
            });
        });
      });

Constant definitions

NameTypeDescription
PRODUCT_KEYStringThe key in the configuration object passed to the ThingAccessClient constructor. It specifies the `productKey` assigned by the cloud.
DEVICE_NAMEStringThe key in the configuration object passed to the ThingAccessClient constructor. It specifies the `deviceName` assigned by the cloud.
LOCAL_NAMEStringThe key in the configuration object passed to the ThingAccessClient constructor. It specifies the custom local device name.
CALL_SERVICEStringThe key in the callback object passed to the ThingAccessClient constructor. It specifies the callback function for calling a device service. For the format of the callback function, see callbacks.callService().
GET_PROPERTIESStringThe key in the callback object passed to the ThingAccessClient constructor. It specifies the callback function for getting device properties. For the format of the callback function, see callbacks.getProperties().
SET_PROPERTIESStringThe key in the callback object passed to the ThingAccessClient constructor. It specifies the callback function for setting device properties. For the format of the callback function, see callbacks.setProperties().
RESULT_SUCCESSNumberThe operation was successful. This is used as a status code returned by a callback function.
RESULT_FAILURENumberThe operation failed. This is used as a status code returned by a callback function.
ERROR_CLEANUPStringThe error code for an error that occurs when you call cleanup().
ERROR_CONNECTStringThe error code for an error that occurs when you call registerAndOnline().
ERROR_DISCONNECTStringThe error code for an error that occurs when you call offline().
ERROR_GET_CONFIGStringThe error code for an error that occurs when you call getConfig().
ERROR_GET_TSLStringThe error code for an error that occurs when you call getTsl().
ERROR_GET_TSL_EXT_INFOStringThe error code for an error that occurs when you call getTslExtInfo().
ERROR_UNREGISTERStringThe error code for an error that occurs when you call unregister().

Config

Provides configuration information for the driver.

  • static get()

    Returns the global driver configuration object. The system automatically generates this configuration when a device is associated with a driver.

    Note The Config.get() method differs from the getConfig() method. getConfig() returns a configuration string, whereas Config.get() returns a configuration object.
    Return value:
    Promise<Config>
  • static registerChangedCallback(callback)

    Registers a callback function for configuration changes.

    Table 1. Request parameters
    NameTypeDescription
    callback(String)FunctionThe callback function. It is called when the configuration changes.
  • static unregisterChangedCallback(callback)

    Unregisters the callback function for configuration changes.

    Table 2. Request parameters
    NameTypeDescription
    callback(String)FunctionThe callback function. It is called when the configuration changes.
  • Config(string)

    Creates a new `Config` object from a configuration string.

    Table 3. Request parameters
    NameTypeDescription
    stringStringA JSON configuration string.
  • getThingInfos()

    Returns information about all devices.

    Return value:
    ThingInfo[]
  • getDriverInfo()

    Returns information about the driver.

    Return value:
    Object

ThingInfo

This class represents a device that is connected to IoT Edge. It contains the device's `productKey`, `deviceName`, and custom configuration.

ThingInfo(productKey, deviceName, custom)

Creates a new `ThingInfo` object.

Table 4. Request parameters
NameTypeDescription
productKeyStringThe unique identifier of the product.
deviceNameStringThe device name.
customObjectThe custom configuration of the device.

ThingAccessClient

This is the device access client. You can use this client to report device properties or events and receive commands from the cloud.

  • ThingAccessClient(config, callbacks)

    Constructor. Creates a client with the specified configuration and callbacks.

    Table 5. Request parameters
    NameTypeDescription
    configObjectMetadata used to configure the client. The format is:
    {
        "productKey": "Your Product Key", 
        "deviceName": "Your Device Name"
    }
    callbacksObjectThe callback function object. The format is:
    callbacks: {
        setProperties: function(properties) {},
        getProperties: function(keys) {},
        callService: function(name, args) {}
    }
    • Specifies the callback parameter for setting device properties. For more information, see callbacks.setProperties in this topic.
    • Specifies the callback parameter for getting device properties. For more information, see callbacks.getProperties in this topic.
    • Specifies the callback parameter for calling a device service. For more information, see callbacks.callService in this topic.
  • callbacks.setProperties(properties)

    A callback function that sets device properties.

    Table 6. Request parameters
    NameTypeDescription
    propertiesObjectThe object for setting properties. The format is:
    {
        "key1": "value1", 
        "key2": "value2"
    }
    Return value:
    {
      "code": 0,
      "message": "string",
      "params": {}
    }
    Table 7. Return parameters
    NameTypeDescription
    codeNumberThe status code.
    • 0: The call was successful.
    • A non-zero value: The call failed and reports the corresponding error.
    messageStringOptional. The status description.
    paramsObjectOptional. Returns the result of setting each property. The value is the actual value of each property after it is set.
  • callbacks.getProperties(keys)

    A callback function that retrieves device properties.

    Table 8. Request parameters
    NameTypeDescription
    keysString[]The names of the properties to get. The format is:
    ['key1', 'key2']
    Return value:
    {
      "code": 0,
      "message": "string",
      "params": {}
    }
    Table 9. Return parameters
    NameTypeDescription
    codeNumberThe status code.
    • 0: The call was successful.
    • A non-zero value: The call failed and reports the corresponding error.
    messageStringOptional. The status description.
    paramsObjectOptional. If the properties are successfully retrieved, this parameter returns the corresponding property values.
  • callbacks.callService(name, args)

    A callback function that calls a device service.

    Table 10. Request parameters
    NameTypeDescription
    nameStringThe service name.
    argsObjectThe list of input parameters for the service. The format is:
    {
        "key1": "value1", 
        "key2": "value2"
    }
    Table 11. Return parameters
    NameTypeDescription
    codeNumberThe status code.
    • 0: The call was successful.
    • A non-zero value: The call failed and reports the corresponding error.
    messageStringOptional. The status description.
    paramsObjectOptional. If the device service is called successfully, this parameter returns additional information.
  • setup()
    Initializes the device access client.
    Important This interface is deprecated in the current version of IoT Edge. Existing calls are not affected.
    Return value:
    Promise<Void>
  • registerAndOnline()

    Registers the device with the gateway and notifies the gateway that the device is online. The device must be registered and online before it can receive commands from the cloud or send data to the cloud.

    Return value:
    Promise<Void>
  • online()

    Notifies the gateway that the device is online. This method is typically called when a device goes online after being offline.

    Return value:
    Promise<Void>
  • offline()

    Alerts you that the gateway device is offline.

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

    Reports a device event.

    Table 12. Request parameters
    NameTypeDescription
    eventNameStringThe name of the event. This must be the same as the event name you created in the product definition.
    argsObjectThe key-value pairs of the properties included in the event. The format is:
    {
        "key1": "value1", 
        "key2": "value2"
    }
  • reportProperties(properties)

    Reports device properties.

    Table 13. Request parameters
    NameTypeDescription
    propertiesObjectThe key-value pairs of the properties. The format is:
    {
        "key1": "value1", 
        "key2": "value2"
    }
  • getTsl()

    Returns the Thing Specification Language (TSL) string. The data format is the same as the format that is used in the cloud.

    Return value:
    Promise<Void>
  • getTslConfig()
    Important This interface is deprecated and has been replaced by the getTslExtInfo() interface. Existing calls are not affected.

    Returns the TSL configuration string.

    Return value:
    Promise<String>
  • getTslExtInfo()

    Returns the TSL extension information string.

    Return value:
    Promise<String>
  • cleanup()

    A resource cleanup method. Use this method to release your resources.

    Return value:
    Promise<Void>
  • unregister()

    Removes the device from the gateway. Use this method with caution.

    Return value:
    Promise<Void>

getConfig()

Retrieves the driver configuration string. The system automatically generates this configuration when a device is associated with a driver.
Note This method differs from the static get() method Config.get(). getConfig() returns a configuration string, whereas Config.get() returns a configuration object.
Return value:
Promise<String>

destroy()

Destroys all internal resources of the library. Call the destroy() method when you no longer need to use the library.

Return value:
Promise<Void>