- DeviceClient
- GatewayClient
- DeviceInfo
- SubDeviceInfo
- SECURE_MODE
Note: There are 2 kinds of parameters in this document:
param: *** indicates a required parameter
[param]: *** indicates an optional parameter
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.
DeviceClient(clientOptions)Arguments
- clientOptions -
Objectrequired for device connection, whose parameters are as follows:- brokerUrl -
stringThe address of EnOS cloud. - secureMode -
SECURE_MODESecurity mode. For the values ofSECURE_MODE, see SECURE_MODE. - productKey -
stringThe product key of a device. - deviceKey -
stringThe device key of a device. - [productSecret] -
stringThe product secret required if you use dynamic authentication. - [deviceSecret] -
stringThe 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] -
stringPrivate 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] -
numberThe longest wating time for connection. The unit being second and the default value 30 seconds. - [reconnectPeriod] -
numberReconnection 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.
- [connectionTimeout] -
- brokerUrl -
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);client.on('connect', () => { console.log('connected') });This event is triggered when a connection or reconnection is established.
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.
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 -
stringTopic of the received message - message -
BufferPayload of the message
client.on('error', (err) => { console.log('err: ', err); })This event is triggered when a parsing error or connection exception occurs.
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:
-
Per-device secret authentication
brokerUrlshould be a TCP-protocol-based url.
secureModeshould be SECURE_MODE.VIA_DEVICE_SECRET.
productKey、deviceKey、deviceSecretare required. -
Per-product secret authentication
brokerUrlshould be a TCP-protocol-based url.
secureModeshould be SECURE_MODE.VIA_PRODUCT_SECRET.
productKey、deviceKey、productSecretare required. -
X.509-certificate-based authentication
brokerUrlshould be a TCP-protocol-based url.
secureModeshould be SECURE_MODE.VIA_DEVICE_SECRET
productKey、deviceKey、deviceSecretare required.
Eitherpfxorkey/certis required.
Response
Promise<string>
- deviceSecret -
stringDevice secret (for dynamic authentication)
Sample
client.connect()
.then(deviceSecret => {
console.log('deviceSecret: ', deviceSecret);
})
.catch(err => {
console.log('err: ', err);
})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);
})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.
Indicates whether the device is reconnected.
For first connection, the value is false.
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.
- [deviceInfo] -
DeviceInfoInformation of the sub-device. Used for indicating sub-devices of a gateway device. - [qos] -
numberLevel of QoS (quality of service). Supports0or1. - [needReply] -
booleanIndicates whether the response from the cloud needs to be waited. The default value istrue.
- response -
UpstreamResponseThe response object.- id -
stringRequest ID. - code -
numberResponse code.200indicates success. - data -
object | string | void. Detailed response information. Explanation is included in the method definitions. - [message] -
stringIf the response code is not200, [message] indicates the exception information.
- id -
function queryTag(queryParams: Object): Promise<UpstreamResponse>Query tag information of devices.
Arguments
- [queryParams] -
ObjectQuery parameter object.- [tagKeys] -
string[]Key-value list for tags. - Common parameters:deviceData/qos/needReply
- [tagKeys] -
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);
})function updateTag(updateParams: Object): Promise<UpstreamResponse>Report tag information
Arguments
- updateParams -
Object- tags -
{tagKey: string, tagValue: string}[]List of tags to be reported. - Common parameters: deviceData/qos/needReply
- tags -
Response
For more information on
UpstreamResponse, see Common response format
- data -
string1will be returned if the update is successful.
Sample
const updateTagResponse = await client.deviceData.updateTag({
tags: [
{tagKey: 'test', tagValue: 'aaaaa'},
{tagKey: 'waitingDelete', tagValue: 'delete'}
]
});function deleteTag(deleteParams: Object): Promise<UpstreamResponse>Delete tag information
Arguments
deleteParams - Object
- tagKeys -
string[]The list of tag keys to be deleted - Common parameters:deviceData/qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
string1will be returned if the deletion is successful.
Sample
const deleteTagResponse = await client.deviceData.deleteTag({
tagKeys: ['waitingDelete']
});function queryAttribute(queryParams: Object): Promise<UpstreamResponse>Get Attribute Information
Arguments
[queryParams] - Object
- [attributeIds] -
string[]List of attribute IDs to be queried. - Common parameters:deviceData/qos/needReply
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: []
});function updateAttribute(updateParams: Object): Promise<UpstreamResponse>Report Attribute Information
Arguments
updateParams - Object
-
attributeMap -
{[x: string]: Object}A map of key-value attribute pairs to be reported// example: { age: 300, name: 'test' }
Response
For more information on
UpstreamResponse, see Common response format
- data -
stringAn 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'
}
}
});function deleteAttribute(deleteParams: Object): Promise<UpstreamResponse>Delete Attribute Information
Arguments
deleteParams - Object
- attributeIds -
string[]List of attribute IDs to be deleted - Common parameters:deviceData/qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
stringAn empty string is returned if the deleting is successful.
Sample
const deleteAttributeResponse = await client.deviceData.deleteAttribute({
attributeIds: ['age']
});function postMeasurepoint(postParams: Object): Promise<UpstreamResponse>Report a Device Measurement Point
Arguments
postParams - Object
- point -
ObjectMeasurement point information to be reported.- measurepoints -
{[x: string]: Object} - [time] -
numberThe timestamp for this measurement point. When not specified, the value is the server time.
- measurepoints -
- 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'
}
}
}
});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 -
string1will 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()
}
});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] -
stringUsed to specify the sub-device of a gateway device - [deviceKey] -
stringUsed to specify the sub-device of a gateway device - measurepoints -
{[x: string]: Object}Measurement point information - [time] -
numberThe timestamp for this measurement point. When not specified, the value is the server time.
- [productKey] -
- [allowOfflineSubDevice] -
booleanWhether 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] -
booleanWhether 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 -
string1will 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()
}
]
});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()
}
]
});function postEvent(postEventParams: Object): Promise<UpstreamResponse>Report Device Events
Arguments
postEventParams - Object
- eventName -
stringEvent name - eventParams -
anyEvent parameters - Common parameters:deviceData/qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
stringAn empty string is returned if the reporting is successful.
Sample
const postEventResponse = await client.deviceData.postEvent({
eventName: 'event_test',
eventParams: {
isMale: 2,
isChild: 10
}
});function upRawModel(rawDataParams: Object): Promise<Buffer>Send raw data such as a binary data stream to the cloud
Arguments
rawDataParams - Object
- rawData -
BufferInformation to be reported - Common parameters:deviceData/qos/needReply
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)
});The methods of device receiving commands from the cloud is included in this attribute.
Command Request Structure CommandRequest
- messageId -
stringMessage ID - version -
stringProtocol version - method -
stringRequest method - params -
anyCommand parameters
Command Response Structure CommandResponse
- send(code, [data], [callback]) -
functionSends response data to cloud- code -
numberError code.200indicates success. - [data] -
ObjectDetailed response information.
- code -
function onInvokeService(serviceName: string, deviceInfo?: DeviceInfo, callback: (request: CommandRequest, response: CommandResponse) => void): Promise<UpstreamResponse>Call Device Services
Arguments
- serviceName -
stringService name - [deviceInfo] -
DeviceInfoSub-device information - callback(request, response) -
functionCallback after receiving a command- request -
CommandRequestSee CommandRequest - response -
CommandResponseSee CommandResponse
- request -
Sample
client.deviceCommand.onInvokeService('resetAge', (request, response) => {
console.log('invoke service request: ', request.params);
response.send(200);
});function onSetMeasurepoint(deviceInfo?: DeviceInfo, callback: (request: CommandRequest, response: CommandResponse) => void): Promise<UpstreamResponse>Set Device Measurements
Arguments
- [deviceInfo] -
DeviceInfoSub-device information - callback(request, response) -
functionCallback after receiving a command- request -
CommandRequestSee CommandRequest - response -
CommandResponseSee CommandResponse
- request -
Sample
client.deviceCommand.onSetMeasurepoint(async(request, response) => {
console.log('set measurepoint request: ', request);
await client.deviceData.postMeasurepoint({
point: {
measurepoints: request.params
}
});
response.send(200);
});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.
Methods of sub-device management are included in this attribute.
- [qos] -
numberQoS level. Supports0 | 1 - [needReply] -
booleanIndicates whether the response from the cloud needs to be waited. The default value istrue
function registerDevice(registerParams: Object): Promise<UpstreamResponse>Registering Devices
Arguments
registerParams - Object
- subDevices -
Object[]- productKey -
stringProduct key of the device. - deviceName - {Object} Name of the device.
- defaultValue -
string - I18nValue -
Object- en_US -
string - zh_CN -
string
- en_US -
- defaultValue -
- timezone -
stringTimezone of the device - [deviceKey] -
stringDevice Key of the device. - [deviceAttributes] -
{[x: string]: ObjectList of the properties of the device. - [deviceDesc] -
stringDescription of the device.
- productKey -
- Common Parameters:qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
Object[]List of devices successfully registered.- assetId -
stringIdentifier of the device - deviceKey -
stringDevice key of the device - productKey -
stringProduct key of the device - deviceSecret -
stringDevice secret of the device
- assetId -
Sample
const registerDeviceResponse = await client.subDeviceManagement.registerDevice({
subDevices: [{
timezone: '+08:00',
productKey: 'productKey',
deviceAttributes: {
name: 'test',
age: 30
},
deviceName: {
defaultValue: 'sdk_demo_name'
}
}]
});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
- productKey -
Sample
const getTopoResonse = await client.subDeviceManagement.getTopo();function addTopo(addParams: Object): Promise<UpstreamResponse>Adding Topological Relationships of Sub-devices
Arguments
addParams - Object
-
subDevices -
(SubDeviceInfo | ISubDeviceCredential)[]SubDeviceInfoSee SubDeviceInfoISubDeviceCredentialThe structure is as follows:
ISubDeviceCredential -
Object
- productKey -
stringProduct key of the sub-device- deviceKey -
stringDevice key of the sub-device- deviceSecret -
stringDevice secret of the sub-device- [clientId] -
stringIdentifier of the sub-device. The value can be productKey or deviceKey.- [timestamp] -
stringTimestamp- [cleanSession] -
booleanIf 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 -
stringAn 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'
}
]
});function deleteTopo(deleteParams: Object): Promise<UpstreamResponse>Deleting Topological Relationships of Sub-devices
Arguments
deleteParams - Object
- subDevices -
Object[]- productKey -
stringProduct key of the sub-device - deviceKey -
stringDevice key of the sub-device
- productKey -
- Common Parameters:qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
stringAn empty string is returned if the deletion is successful.
Sample
const deleteTopoResponse = await client.subDeviceManagement.deleteTopo({
subDevices: [{
productKey: 'productKey',
deviceKey: 'deviceKey'
}]
});function loginSubDevice(loginParams: Object): Promise<UpstreamResponse>Connecting Sub-devices
Arguments
loginParams - Object
-
subDevice -
SubDeviceInfo | ISubDeviceCredentialSubDeviceInfoSee SubDeviceInfoISubDeviceCredentialSee ISubDeviceCredential
Response
For more information on
UpstreamResponse, see Common response format
- data -
ObjectInformation of sub-devices that are connected successfully.- assetId -
string - deviceKey -
string - productKey -
string
- assetId -
Sample
const loginSubDeviceResponse = await client.subDeviceManagement.loginSubDevice({
subDevice: {
productKey: 'productKey',
deviceKey: 'deviceKey',
deviceSecret: 'deviceSecret'
}
});function logoutSubDevice(logoutParams: Object): Promise<UpstreamResponse>Disconnecting Sud-devices
Arguments
logoutParams - Object
- subDevice -
Object- productKey -
stringProduct key of the sub-device - deviceKey -
stringDevice key of the sub-device
- productKey -
- Common Parameters:qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
Object[]Information of disconnected sub-devices- deviceKey -
stringDevice key of the sub-device - productKey -
stringProduct key of the sub-device
- deviceKey -
Sample
function batchLoginSubDevice(loginParams: Object): Promise<UpstreamResponse>Connecting Sub-devices in Batch
Arguments
loginParams - Object
- subDevices -
(SubDeviceInfo | ISubDeviceCredential)[]SubDeviceInfoSee SubDeviceInfoISubDeviceCredentialSee ISubDeviceCredential - [clientId] -
stringThe identifier of the device. The value can be productKey or deviceName. - [timestamp] -
stringTimestamp - Common Parameters:qos/needReply
Response
For more information on
UpstreamResponse, see Common response format
- data -
ObjectLogin result- loginedSubDevices -
Object[]Devices that successfully logged in.- assetId -
string - deviceKey -
string - productKey -
string
- assetId -
- failedSubDevices -
Object[]Devices that failed to log in.- productKey -
string - deviceKey -
string
- productKey -
- loginedSubDevices -
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'
}
]
});function onSubDevicesEnable(callback: (request: CommandRequest, response: CommandResponse) => void): voidEnabling Sub-devices
Arguments
- callback(request, response) -
functionCallback after a command is received.- request -
CommandRequestSee CommandRequest - response -
CommandResponseSee CommandResponse
- request -
Sample
client.subDeviceManagement.onSubDevicesEnable((request, response) => {
response.send(200);
});function onSubDevicesDisable(callback: (request: CommandRequest, response: CommandResponse) => void): voidDisabling Sub-devices
Arguments
- callback(request, response) -
functionCallback after a command is received- request -
CommandRequestSee CommandRequest - response -
CommandResponseSee CommandResponse
- request -
Sample
client.subDeviceManagement.onSubDevicesDisable((request, response) => {
response.send(200);
});function onSubDevicesDelete(callback: (request: CommandRequest, response: CommandResponse) => void): voidDeleting Sub-devices
Arguments
- callback(request, response) -
functionCallback after a command is received- request -
CommandRequestSee CommandRequest - response -
CommandResponseSee CommandResponse
- request -
Sample
client.subDeviceManagement.onSubDevicesDelete((request, response) => {
response.send(200);
});DeviceInfo(deviceInfo)Arguments
- deviceInfo -
Object- productKey -
stringProduct key of the device - deviceKey -
stringDevice key of the device - [productSecret] -
stringProduct secret of the device - [deviceSecret] -
stringDevice secret of the device
- productKey -
Product key of the device
Device key of the device
Product secret of the device
Device secret of the device
SubDeviceInfo(subDeviceInfo)Arguments
- subDeviceInfo -
Object- productKey -
stringProduct key of the sub-device - deviceKey -
stringDevice key of the sub-device - [productSecret] -
stringProduct secret of the sub-device - [deviceSecret] -
stringDevice secret of the sub-device - [timestamp] -
numberTimestamp - [clientId] -
stringIdentifier of the sub-device - [cleanSession] -
booleanIf 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.
- productKey -
Product key of the sub-device
Device key of the sub-device
Product secret of the sub-device
Device secret of the sub-device
Timestamp
Identifier of the sub-device
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.
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