Skip to content

Latest commit

 

History

History
1358 lines (970 loc) · 34.5 KB

File metadata and controls

1358 lines (970 loc) · 34.5 KB

API Reference

Note: There are 2 kinds of parameters in this document:
param: *** indicates a required parameter
[param]: *** indicates an optional parameter

DeviceClient

Core class that can establish connection between a device and EnOS Cloud.
After a connection is established, you can call the methods of this class to make the device report data to and receive commands from EnOS cloud.
As this class is inherited from events.EventEmitter, relevent events will be triggered when a connection is established, a command is received, or a connection is closed. For more information, see Events.


Constructor

DeviceClient(clientOptions)

Arguments

  • clientOptions - Object required for device connection, whose parameters are as follows:
    • brokerUrl - string The address of EnOS cloud.
    • secureMode - SECURE_MODE Security mode. For the values of SECURE_MODE, see SECURE_MODE.
    • productKey - string The product key of a device.
    • deviceKey - string The device key of a device.
    • [productSecret] - string The product secret required if you use dynamic authentication.
    • [deviceSecret] - string The device secret required if you use static authentication.
    • [ca] - string | Buffer | Array<string | Buffer> Root certificate, required if you use certificate-based authentication.
    • [pfx] - string | Buffer | Array<string | Buffer | Object> Private key + device certificate.
    • [passphrase] - string Private key password.
    • [key] - string | Buffer | Array<string | Buffer | Object> Private key on the device side
    • [cert] - string | Buffer | Array<string | Buffer> Device certificate
    • [mqttOptions] - MQTT-specific parameter, which includes the following:
      • [connectionTimeout] - number The longest wating time for connection. The unit being second and the default value 30 seconds.
      • [reconnectPeriod] - number Reconnection interval, the unit being second. The default value is 3 seconds, indicating that reconnection is attempted every 3 seconds. 0 indicates the reconnection is disabled.
      • [keepAlive] - number. The unit is second and default value 60 seconds. 0 indicates the keepAlive is disabled.

Sample

const clientOptions = {
  brokerUrl: 'brokerUrl',
  secureCode: SECURE_MODE.VIA_DEVICE_SECRET,
  productKey: 'productKey', deviceKey: 'deviceKey', deviceSecret: 'deviceSecret',
  mqttOptions: {
    connectionTimeout: 30,
    reconnectPeroid: 0, // The reconnection is disabled.
    keepAlive: 0 // The keepAlive disalbed.
  }
}
const client = new DeviceClient(clientOptions);

Events

Event 'connect'

client.on('connect', () => { console.log('connected') });

This event is triggered when a connection or reconnection is established.

Event 'close'

client.on('close', () => { console.log('connection is disconnected') });

This event is triggered when a connection is closed, whether manually or due to an exception.

If reconnectPeriod is not 0 when the connection is established, and the connection is not closed manually, a reconnection will be initiated after a close event.

Event 'message'

client.on('message', (topic, message) => {
  console.log(`${topic}:${message}`);
})

This event is triggered when a command or message response from the cloud is received

  • topic - string Topic of the received message
  • message - Buffer Payload of the message

Event 'error'

client.on('error', (err) => { console.log('err: ', err); })

This event is triggered when a parsing error or connection exception occurs.


Methods

connect()

function connect(): Promise<string>

Establishing a connection between a device and the cloud.
An event named connect is triggered when the connection is established successfully.
The authentication modes for the connection between a device and EnOS Cloud are as follows, corresponding to the different parameter values to clientOptions in Constructor:

  1. Per-device secret authentication
    brokerUrl should be a TCP-protocol-based url.
    secureMode should be SECURE_MODE.VIA_DEVICE_SECRET.
    productKey、deviceKey、deviceSecret are required.

  2. Per-product secret authentication
    brokerUrl should be a TCP-protocol-based url.
    secureMode should be SECURE_MODE.VIA_PRODUCT_SECRET.
    productKey、deviceKey、productSecretare required.

  3. X.509-certificate-based authentication
    brokerUrl should be a TCP-protocol-based url.
    secureMode should be SECURE_MODE.VIA_DEVICE_SECRET
    productKey、deviceKey、deviceSecret are required.
    Either pfx or key/cert is required.

Response

Promise<string>

  • deviceSecret - string Device secret (for dynamic authentication)

Sample

client.connect()
  .then(deviceSecret => {
    console.log('deviceSecret: ', deviceSecret);
  })
  .catch(err => {
    console.log('err: ', err);
  })

close()

function close(): Promise<void>

Closing a connection between a device and the cloud.
An event named close is triggered after the connection to the cloud is closed.

Sample

client.close()
  .then(() => {
    console.log('connection closed')
  })
  .catch(err => {
    console.log('err: ', err);
  })

Properties

connected boolean

Indicates whether or not the device is connected to the cloud.
For first connection and reconnection, the value is true. For disconnected connection, the value is false.

reconnected boolean

Indicates whether the device is reconnected.
For first connection, the value is false.

deviceData Object

Methods for reporting data is included in this attribute. These methods have common request parameters and response values. In the following explanation, common parameters will be omitted in request parameters. In the response, only unique elements in data will be explained.

Common request parameters

  • [deviceInfo] - DeviceInfo Information of the sub-device. Used for indicating sub-devices of a gateway device.
  • [qos] - number Level of QoS (quality of service). Supports 0 or 1.
  • [needReply] - boolean Indicates whether the response from the cloud needs to be waited. The default value is true.

Common response structure

  • response - UpstreamResponse The response object.
    • id - string Request ID.
    • code - number Response code. 200 indicates success.
    • data - object | string | void. Detailed response information. Explanation is included in the method definitions.
    • [message] - string If the response code is not 200, [message] indicates the exception information.

deviceData#queryTag(queryParams)

function queryTag(queryParams: Object): Promise<UpstreamResponse>

Query tag information of devices.

Arguments

Response

For more information on the response object UpstreamResponse, see Common response format

  • data - {key: value} Key-value pair for tag.

    { key1: 'value1', key2: 'value2' }

Sample

client.deviceData.queryTag()
  .then(response => {
    console.log(response.code, response.data);
  })
  .catch(err => {
    console.log('err: ', err);
  })

deviceData.updateTag(updateParams)

function updateTag(updateParams: Object): Promise<UpstreamResponse>

Report tag information

Arguments

Response

For more information on UpstreamResponse, see Common response format

  • data - string 1 will be returned if the update is successful.

Sample

const updateTagResponse = await client.deviceData.updateTag({
  tags: [
    {tagKey: 'test', tagValue: 'aaaaa'},
    {tagKey: 'waitingDelete', tagValue: 'delete'}
  ]
});

deviceData#deleteTag(deleteParams)

function deleteTag(deleteParams: Object): Promise<UpstreamResponse>

Delete tag information

Arguments

deleteParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - string 1 will be returned if the deletion is successful.

Sample

const deleteTagResponse = await client.deviceData.deleteTag({
  tagKeys: ['waitingDelete']
});

deviceData#queryAttribute(queryParams)

function queryAttribute(queryParams: Object): Promise<UpstreamResponse>

Get Attribute Information

Arguments

[queryParams] - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - Object. Attribute map obtained. For example, {age: 30}.

Sample

const queryAttributeResponse = await client.deviceData.queryAttribute({
  attributeIds: []
});

deviceData#updateAttribute(updateParams)

function updateAttribute(updateParams: Object): Promise<UpstreamResponse>

Report Attribute Information

Arguments

updateParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - string An empty string is returned if the update is successful.

Sample

const updateAttributeResponse = await client.deviceData.updateAttribute({
  attributeMap: {
    age: 900,
    attribute_struct: {
      struct_int: 10,
      struct_string: 'test'
    }
  }
});

deviceData#deleteAttribute(deleteParams)

function deleteAttribute(deleteParams: Object): Promise<UpstreamResponse>

Delete Attribute Information

Arguments

deleteParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - string An empty string is returned if the deleting is successful.

Sample

const deleteAttributeResponse = await client.deviceData.deleteAttribute({
  attributeIds: ['age']
});

deviceData#postMeasurepoint(postParams)

function postMeasurepoint(postParams: Object): Promise<UpstreamResponse>

Report a Device Measurement Point

Arguments

postParams - Object

  • point - Object Measurement point information to be reported.
    • measurepoints - {[x: string]: Object}
    • [time] - number The timestamp for this measurement point. When not specified, the value is the server time.
  • Common parameters:deviceData/qos/needReply

Response

For more information on UpstreamResponse, see Common response format

  • data - string

Sample

const postMpResponse = await client.deviceData.postMeasurepoint({
  point: {
    measurepoints: {
      mp_struct: {
        sub_age: 100,
        sub_gender: 'male'
      }
    }
  }
});

deviceData#resumeMeasurepoint(resumeParams)

function resumeMeasurepoint(resumeParams: Object): Promise<UpstreamResponse>

Report an Offline Measurement Point

Arguments

resumeParams - Object Same as in postMeasurepoint

Response

For more information on UpstreamResponse, see Common response format

  • data - string 1 will be returned if the reporting is successful.

Sample

const resumeMpResponse = await client.deviceData.resumeMeasurepoint({
  point: {
    measurepoints: {
      mp_struct: {
        sub_age: 50,
        sub_gender: 'female'
      }
    },
    time: new Date('2019-12-11 00:00').getTime()
  }
});

deviceData#batchPostMeasurepoint(postParams)

function batchPostMeasurepoint(postParams: Object): Promise<UpstreamResponse>

Report Measurement Points in Batch

Measurement points are reported in batch in the following scenarios:

  • A gateway device reports the measurement point data of its sub-devices.
  • A device that is directly connected to EnOS reports data of different timestamps.
  • A mixture of the previous two scenarios.

Arguments

postParams - Object

  • points - Object[] List of measurement points to be reported
    • [productKey] - string Used to specify the sub-device of a gateway device
    • [deviceKey] - string Used to specify the sub-device of a gateway device
    • measurepoints - {[x: string]: Object} Measurement point information
    • [time] - number The timestamp for this measurement point. When not specified, the value is the server time.
  • [allowOfflineSubDevice] - boolean Whether to allow sending measurement point data for offline devices. False by default. If sending data of offline device is not allowed and the request contains an offline device, the entire request is declined.
  • [skipInvalidMeasurepoints] - boolean Whether to neglect invalid measurement point data in a request. False by default. If the value is set to false and the request contains invalid measurement point data, the entire request is declined.
  • Common Parameters:deviceData/qos/needReply

Response

For more information on UpstreamResponse, see Common response format

  • data - string 1 will be returned if the reporting is successful.

Sample

const batchPostMpResponse = await client.deviceData.batchPostMeasurepoint({
  points: [
    {
      measurepoints: {
        mp_age: 50
      }
    },
    {
      measurepoints: {
        mp_age: 10
      },
      time: new Date('2019-10-20 20:00').getTime()
    }
  ]
});

deviceData#batchResumeMeasurepoint(resumeParams)

function batchResumeMeasurepoint(resumeParams: Object): Promise<UpstreamResponse>

Report Offline Measurement Points in Batch

Offline measurement points are reported in batch in the following scenarios:

  • A gateway device reports the measurement point data of its sub-devices.
  • A device that is directly connected to EnOS reports data of different timestamps.
  • A mixture of the previous two scenarios.

Arguments

resumeParams - Object Same as in batchPostMeasurepoint

Response

Same as in batchPostMeasurepoint

Sample

const batchResumeMpResponse = await client.deviceData.batchResumeMeasurepoint({
  points: [
    {
      measurepoints: {
        mp_age: 200
      }
    },
    {
      measurepoints: {
        mp_age: 30
      },
      time: new Date('2019-10-20 20:00').getTime()
    }
  ]
});

deviceData#postEvent(postEventParams)

function postEvent(postEventParams: Object): Promise<UpstreamResponse>

Report Device Events

Arguments

postEventParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - string An empty string is returned if the reporting is successful.

Sample

const postEventResponse = await client.deviceData.postEvent({
  eventName: 'event_test',
  eventParams: {
    isMale: 2,
    isChild: 10
  }
});

deviceData#upRawModel(rawDataParams)

function upRawModel(rawDataParams: Object): Promise<Buffer>

Send raw data such as a binary data stream to the cloud

Arguments

rawDataParams - Object

Response

Promise The response of this method is Buffer

Sample

const rawData = [0x00, 0x00, 0x00, 0x14];
const rawDataResult = await client.deviceData.upRawModel({
  rawData: Buffer.from(rawData)
});

deviceCommand Object

The methods of device receiving commands from the cloud is included in this attribute.

Command Request Structure CommandRequest

  • messageId - string Message ID
  • version - string Protocol version
  • method - string Request method
  • params - any Command parameters

Command Response Structure CommandResponse

  • send(code, [data], [callback]) - function Sends response data to cloud
    • code - number Error code. 200 indicates success.
    • [data] - Object Detailed response information.

deviceCommand#onInvokeService(serviceName, [deviceInfo], callback)

function onInvokeService(serviceName: string, deviceInfo?: DeviceInfo, callback: (request: CommandRequest, response: CommandResponse) => void): Promise<UpstreamResponse>

Call Device Services

Arguments

  • serviceName - string Service name
  • [deviceInfo] - DeviceInfo Sub-device information
  • callback(request, response) - function Callback after receiving a command

Sample

client.deviceCommand.onInvokeService('resetAge', (request, response) => {
  console.log('invoke service request: ', request.params);
  response.send(200);
});

deviceCommand#onSetMeasurepoint([deviceInfo], callback)

function onSetMeasurepoint(deviceInfo?: DeviceInfo, callback: (request: CommandRequest, response: CommandResponse) => void): Promise<UpstreamResponse>

Set Device Measurements

Arguments

  • [deviceInfo] - DeviceInfo Sub-device information
  • callback(request, response) - function Callback after receiving a command

Sample

client.deviceCommand.onSetMeasurepoint(async(request, response) => {
  console.log('set measurepoint request: ', request);
  await client.deviceData.postMeasurepoint({
    point: {
      measurepoints: request.params
    }
  });
  response.send(200);
});

GatewayClient

Inherited from DeviceClient. It has the same capability as DeviceClient and sub-device management capability.

A gateway device uses this client to communicate with the cloud.

Sample Attribute:

subDeviceManagement

Methods of sub-device management are included in this attribute.

Common Request Parameters

  • [qos] - number QoS level. Supports 0 | 1
  • [needReply] - boolean Indicates whether the response from the cloud needs to be waited. The default value is true

subDeviceManagement#registerDevice(registerParams)
function registerDevice(registerParams: Object): Promise<UpstreamResponse>

Registering Devices

Arguments

registerParams - Object

  • subDevices - Object[]
    • productKey - string Product key of the device.
    • deviceName - {Object} Name of the device.
      • defaultValue - string
      • I18nValue - Object
        • en_US - string
        • zh_CN - string
    • timezone - string Timezone of the device
    • [deviceKey] - string Device Key of the device.
    • [deviceAttributes] - {[x: string]: Object List of the properties of the device.
    • [deviceDesc] - string Description of the device.
  • Common Parameters:qos/needReply

Response

For more information on UpstreamResponse, see Common response format

  • data - Object[] List of devices successfully registered.
    • assetId - string Identifier of the device
    • deviceKey - string Device key of the device
    • productKey - string Product key of the device
    • deviceSecret - string Device secret of the device

Sample

const registerDeviceResponse = await client.subDeviceManagement.registerDevice({
  subDevices: [{
    timezone: '+08:00',
    productKey: 'productKey',
    deviceAttributes: {
      name: 'test',
      age: 30
    },
    deviceName: {
      defaultValue: 'sdk_demo_name'
    }
  }]
});

subDeviceManagement#getTopo(queryParams)
function getTopo(queryParams: Object): Promise<UpstreamResponse>

Getting Topological Relationships of Sub-devices

Arguments

[queryParams] - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - Object[] List of sub-devices
    • productKey - string
    • productName - string
    • iotId - string
    • deviceKey - string
    • deviceSecret - string
    • deviceAttributes - [x: string]: Object
    • deviceName - string
    • timezone - string
    • isDST - boolean
    • topo - string
    • orgCode - string
    • createBy - string
    • gmtCreate - number
    • modifiedByOrg - string
    • modifiedBy - string
    • gmtModified - number
    • gmtActive - number
    • gmtOnline - number
    • gmtOffline - number
    • status - string
    • nodeType - number
    • dataType - number

Sample

const getTopoResonse = await client.subDeviceManagement.getTopo();

subDeviceManagement#addTopo(registerParams)
function addTopo(addParams: Object): Promise<UpstreamResponse>

Adding Topological Relationships of Sub-devices

Arguments

addParams - Object

ISubDeviceCredential - Object

  • productKey - string Product key of the sub-device
  • deviceKey - string Device key of the sub-device
  • deviceSecret - string Device secret of the sub-device
  • [clientId] - string Identifier of the sub-device. The value can be productKey or deviceKey.
  • [timestamp] - string Timestamp
  • [cleanSession] - boolean If the value is true, it indicates to clear offline information for all sub-devices, which is information that has not been received by QoS 1.

Response

For more information on UpstreamResponse, see Common response format

  • data - string An empty string is returned if the adding is successful.

Sample

const subDeviceInfo = new SubDeviceInfo({
  productKey: 'productKey',
  deviceKey: 'deviceKey',
  deviceSecret: 'deviceSecret'
});
const addTopoResponse = await client.subDeviceManagement.addTopo({
  subDevices: [
    subDeviceInfo,
    {
      productKey: 'productKey',
      deviceKey: 'deviceKey',
      deviceSecret: 'deviceSecret'
    }
  ]
});

subDeviceManagement#deleteTopo(registerParams)
function deleteTopo(deleteParams: Object): Promise<UpstreamResponse>

Deleting Topological Relationships of Sub-devices

Arguments

deleteParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - string An empty string is returned if the deletion is successful.

Sample

const deleteTopoResponse = await client.subDeviceManagement.deleteTopo({
  subDevices: [{
    productKey: 'productKey',
    deviceKey: 'deviceKey'
  }]
});

subDeviceManagement#loginSubDevice(loginParams)
function loginSubDevice(loginParams: Object): Promise<UpstreamResponse>

Connecting Sub-devices

Arguments

loginParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - Object Information of sub-devices that are connected successfully.
    • assetId - string
    • deviceKey - string
    • productKey - string

Sample

const loginSubDeviceResponse = await client.subDeviceManagement.loginSubDevice({
  subDevice: {
    productKey: 'productKey',
    deviceKey: 'deviceKey',
    deviceSecret: 'deviceSecret'
  }
});

subDeviceManagement#logoutSubDevice(logoutParams)
function logoutSubDevice(logoutParams: Object): Promise<UpstreamResponse>

Disconnecting Sud-devices

Arguments

logoutParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - Object[] Information of disconnected sub-devices
    • deviceKey - string Device key of the sub-device
    • productKey - string Product key of the sub-device

Sample


subDeviceManagement#batchLoginSubDevice(loginParams)
function batchLoginSubDevice(loginParams: Object): Promise<UpstreamResponse>

Connecting Sub-devices in Batch

Arguments

loginParams - Object

Response

For more information on UpstreamResponse, see Common response format

  • data - Object Login result
    • loginedSubDevices - Object[] Devices that successfully logged in.
      • assetId - string
      • deviceKey - string
      • productKey - string
    • failedSubDevices - Object[] Devices that failed to log in.
      • productKey - string
      • deviceKey - string

Sample

const subDeviceInfo = new SubDeviceInfo({
  productKey: 'productKey',
  deviceKey: 'deviceKey',
  deviceSecret: 'deviceSecret'
});
const batchLoginResponse = await client.subDeviceManagement.batchLoginSubDevice({
  subDevices: [
    subDeviceInfo,
    {
      productKey: 'productKey',
      deviceKey: 'deviceKey',
      deviceSecret: 'deviceSecret'
    }
  ]
});

subDeviceManagement#onSubDevicesEnable(callback)
function onSubDevicesEnable(callback: (request: CommandRequest, response: CommandResponse) => void): void

Enabling Sub-devices

Arguments

  • callback(request, response) - function Callback after a command is received.

Sample

client.subDeviceManagement.onSubDevicesEnable((request, response) => {
  response.send(200);
});

subDeviceManagement#onSubDevicesDisable(callback)
function onSubDevicesDisable(callback: (request: CommandRequest, response: CommandResponse) => void): void

Disabling Sub-devices

Arguments

  • callback(request, response) - function Callback after a command is received

Sample

client.subDeviceManagement.onSubDevicesDisable((request, response) => {
  response.send(200);
});

subDeviceManagement#onSubDevicesDelete(callback)
function onSubDevicesDelete(callback: (request: CommandRequest, response: CommandResponse) => void): void

Deleting Sub-devices

Arguments

  • callback(request, response) - function Callback after a command is received

Sample

client.subDeviceManagement.onSubDevicesDelete((request, response) => {
  response.send(200);
});

DeviceInfo

Constructor

DeviceInfo(deviceInfo)

Arguments

  • deviceInfo - Object
    • productKey - string Product key of the device
    • deviceKey - string Device key of the device
    • [productSecret] - string Product secret of the device
    • [deviceSecret] - string Device secret of the device

Properties

productKey string

Product key of the device

deviceKey string

Device key of the device

productSecret string

Product secret of the device

deviceSecret string

Device secret of the device


SubDeviceInfo

Constructor

SubDeviceInfo(subDeviceInfo)

Arguments

  • subDeviceInfo - Object
    • productKey - string Product key of the sub-device
    • deviceKey - string Device key of the sub-device
    • [productSecret] - string Product secret of the sub-device
    • [deviceSecret] - string Device secret of the sub-device
    • [timestamp] - number Timestamp
    • [clientId] - string Identifier of the sub-device
    • [cleanSession] - boolean If the value is set to true, it indicates to clear offline information for all sub-devices, which is information that has not been received by QoS 1.

Properties

productKey string

Product key of the sub-device

deviceKey string

Device key of the sub-device

productSecret string

Product secret of the sub-device

deviceSecret string

Device secret of the sub-device

timestamp number

Timestamp

clientId string

Identifier of the sub-device

cleanSession boolean

If the value is set to true, it indicates to clear offline information for all sub-devices, which is information that has not been received by QoS 1.


SECURE_MODE

Authentication mode. Used when creating a client instance.

const clientOptions = {..., secureMode: SECURE_MODE.VIA_DEVICE_SECRET}
  • VIA_DEVICE_SECRET - Use static authentication
  • VIA_PRODUCT_SECRET - Use dynamic authentication