@8devices/restserver-api 中文文档教程

发布于 6年前 浏览 30 项目主页 更新于 3年前

构建状态codecov

restserver-api

示例程序 此示例显示了基本的 restserver-api 用法。

const restAPI = require('restserver-api');

const { Lwm2m } = restAPI;
const { RESOURCE_TYPE, encodeResource, decodeResource } = Lwm2m.TLV;

console.log('Initialize service and endpoint');
const service = new restAPI.Service();
const device = new restAPI.Device(service, 'urn:uuid:17200d69-ec9b-43b3-9051-73df2207907c');

console.log('Encode resource to TLV format');
const tlvBuffer = encodeResource({
  identifier: 3,
  type: RESOURCE_TYPE.INTEGER,
  value: 60
});

console.log('Start service');
service.start().then(() => {
  console.log('Service started');
  console.log('Writing into device\'s resource');
  device.write('/3/0/7', (status) => {
    console.log('Received response with status: ', status);
    console.log('Stopping service');
    service.stop().then(() => {
      console.log('Service stopped');
    });
  }, tlvBuffer);
});

Classes

Device

此类表示设备(端点)。

Service

此类表示 REST API 服务。

Constants

TYPE

表示 LwM2M 变量(标识符)类型(OBJECT_INSTANCE, 多个资源、资源实例、资源)。

RESOURCE_TYPE

表示资源类型(NONE、BOOLEAN、INTEGER、FLOAT、STRING、OPAQUE)。

Functions

getDictionaryByValue(dictionaryList, keyName, value)Object | string | number

通过键和值的给定名称获取字典。

encodeResourceValue(resource)object

对资源的值进行编码。

decodeResourceValue(buffer, resource)Object | string | number | boolean

解码资源的价值。

encode(object)object

编码 ant 类型的实例(对象实例、多个资源、资源实例、资源)。

encodeResourceInstance(resourceInstance)object

将资源实例编码到 TLV 缓冲区。

encodeMultipleResourcesTLV(resources)object

将多个资源值编码到 TLV 缓冲区。

encodeResource(resource)object

将资源编码到 TLV 缓冲区。

encodeObjectInstance(objectInstance)object

将 LwM2M 对象实例编码到 TLV 缓冲区。

encodeObject(object)object

将 LwM2M 对象编码到 TLV 缓冲区。

decode(buffer)object

解码任何 TLV 缓冲区。

decodeResourceInstance(buffer, resources)object

解码资源实例。

decodeResourceInstanceValue(buffer, resourceInstance)object

解码资源实例值

decodeResource(buffer, resource)object

解码资源。

decodeObjectInstance(buffer, objectInstance)object

从 TLV 缓冲区解码对象实例。

decodeObject(buffer, object)object

将 LwM2M 对象解码到 TLV 缓冲区。

Device

这个类表示设备(端点)。

Kind:全局类

new Device(service, id)

构造函数初始化给定的服务对象,设备的 id 并开始监听服务发出的事件(当设备 注册、更新、注销、发送数据),处理“异步 响应”并发出“注册”、“更新”、“取消注册”事件。

ParamTypeDescription
serviceobjectService object
idstringEndpoint id

示例

const restAPI = require('restserver-api');

const service = new restAPI.Service(serviceOptions);
const device = new restAPI.Device(service, 'deviceId');

device.getObjects() ⇒ Promise

发送请求以获取所有设备的对象。

KindDevice
的实例方法 返回Promise - Promise 对象与设备的对象
示例

device.getObjects().then((resp) => {
  // resp = [ { uri: '/1/0' }, { uri: '/2/0' }, ... ]
}).catch((err) => {
  // err - exception message object or status code
});

device.read(path, callback) ⇒ Promise

发送读取设备资源数据的请求。

种类Device
的实例方法 返回Promise - Promise with async response id

ParamTypeDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received

Example

device.read(path, (status, payload) => {
  // status = 200
  // payload = 4RbaAA==
}).then((asyncResponseId) => {
  // asyncResponseId = 1533889157#42f26784-1a8d-4861-36aa-d88f
}).catch((err) => {
  // err - exception object or status code
});

device.write(path, callback, payload, type) ⇒ Promise

发送写入请求价值转化为设备的资源。

种类Device
的实例方法 返回Promise - 具有异步响应 ID

ParamTypeDefaultDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received
payloadbufferData (optional)
typestring"application/vnd.oma.lwm2m+tlv"Content type (optional)

Example

device.write(path, (status) => {
  // status = 202
}, payload).then((asyncResponseId) => {
  // asyncResponseId = 1533889926#870a3f17-3e21-b6ad-f63d-5cfe
}).catch((err) => {
  // err - exception object or status code
});

device.execute(path, callback, payload, type) ⇒ Promise

发送请求以执行设备的 Promise资源。

种类Device
的实例方法 返回Promise - 具有异步响应 id

ParamTypeDefaultDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received
payloadbufferData (optional)
typestring"text/plain"Content type (optional)

Example

device.execute(path, (status) => {
  // status = 202
}).then((asyncResponseId) => {
  // asyncResponseId = 1533889926#870a3f17-3e21-b6ad-f63d-5cfe
}).catch((err) => {
  // err - exception object or status code
});

device.observe(path, callback) ⇒ Promise

发送订阅请求资源。

种类Device
的实例方法 返回Promise - 带有异步响应id的Promise

ParamTypeDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received

Example

device.observe(path, (status, payload) => {
  // status = 200
  // payload = 4RbaAA==
}).then((asyncResponseId) => {
  // asyncResponseId = 1533889157#42f26784-1a8d-4861-36aa-d88f
}).catch((err) => {
  // err - exception object or status code
});

device.cancelObserve(path) ⇒ Promise

发送取消订阅的请求.

种类Device
的实例方法 返回Promise - 带有 HTTP 状态代码的 Promise

ParamTypeDescription
pathstringResource path

Example

device.cancelObserve(path).then((status) => {
  // status - status code
}).catch((err) => {
  // err - exception object
});

Service

此类表示 REST API 服务。

种类:全局类

new Service(opts)

初始化默认配置。 使用给定的选项重新配置。

ParamTypeDescription
optsobjectOptions object (optional)

示例

const options = {
  // REST server's address
  host: 'http://localhost:8888',
  // CA certificate
  ca: '',
  // authentication (true or false)
  authentication: false,
  username: '',
  password: '',
  // notification polling (true or false)
  polling: false,
  // time between each poll in miliseconds
  interval: 1234,
  // port for socket listener (not relevant if polling is enabled)
  port: 5728,
};
new Service(options);

service.start(opts) ⇒ Promise

(Re)starts authentication, 套接字监听器创建和通知回调注册 或通知轮询过程。

KindService
的实例方法 返回Promise - 在服务启动时实现的Promise

ParamTypeDescription
optsobjectOptions object (optional)

Example

service.start().then(() => {
  // started service
}).catch((err) => {
  // err - exception object
});

Example (传递选项对象)< /em>

const options = {
  // REST server's address
  host: 'http://localhost:8888',
  // CA certificate
  ca: '',
  // authentication (true or false)
  authentication: false,
  username: '',
  password: '',
  // notification polling (true or false)
  polling: false,
  // time between each poll in miliseconds
  interval: 1234,
  // port for socket listener (not relevant if polling is enabled)
  port: 5728,
};
service.start(options);

service.stop() ⇒ Promise

停止接收和处理事件 停止此服务及其所有子服务 在 start() 中启动的。 清理资源

KindService
的实例方法 返回Promise - 在服务停止时实现的Promise
示例

service.stop().then(() => {
  // stopped service
});

service.authenticate() ⇒ Promise

发送请求以验证用户。

KindService
的实例方法 返回Promise - 带有身份验证数据的 Promise(令牌及其过期时间)
示例

service.authenticate().then((resp) => {
  // resp = { access_token: 'token-value', expires_in: 3600 }
}).catch((err) => {
  // err - exception message object or status code
});

service.registerNotificationCallback() ⇒ Promise

发送注册通知回调的请求。

KindService
的实例方法 返回Promise - 在注册通知回调时实现的Promise
示例

service.registerNotificationCallback().then(() => {
  // notification callback has been registered
}).catch((err) => {
  // err - exception object or status code
});

service.deleteNotificationCallback() ⇒ Promise

发送请求以删除通知回调。

KindService
的实例方法 返回Promise - 带有 HTTP 状态代码的 Promise
示例

service.deleteNotificationCallback().then((status) => {
  // status - status code
}).catch((err) => {
  // err - exception object
});

service.checkNotificationCallback() ⇒ Promise

发送请求以检查是否注册了通知回调。

KindService
的实例方法 返回Promise - 带有通知回调数据的Promise
示例

service.checkNotificationCallback().then((resp) => {
  // resp = { url: 'http://localhost:5728/notification', headers: {} }
}).catch((err) => {
  // err - exception message object or status code
});

service.pullNotification() ⇒ Promise

发送请求以获取挂起/排队的通知。

KindService
的实例方法 返回Promise - Promise 与通知数据(注册, 注销、更新、异步响应)
示例

service.pullNotification().then((resp) => {
  // resp = { registrations: [...], 'reg-updates': [...], ... }
}).catch((err) => {
  // err - exception object
});

service.getDevices() ⇒ Promise

发送请求以获取所有已注册的端点。

KindService
的实例方法 返回Promise - 带有端点列表的Promise
示例

service.getDevices().then((resp) => {
  // resp = [ { name: 'uuid-4567', type: '8dev_3700', ... }, ... ]
}).catch((err) => {
  // err - exception message object or status code
});

service.getVersion() ⇒ Promise

发送请求以获取 REST 服务器版本。

KindService
的实例方法 返回Promise - 使用 REST 服务器版本的 Promise
示例

service.getVersion().then((resp) => {
  // resp = '1.0.0'
}).catch((err) => {
  // err - exception object
});

service.get(path) ⇒ Promise

使用给定路径执行 GET 请求。

KindService
的实例方法 返回Promise - Promise with data and response object

ParamTypeDescription
pathstringRequest path

Example

service.get(path).then((dataAndResponse) => {
  // dataAndResponse.data - data object
  // dataAndResponse.resp - response object
}).catch((err) => {
  // err - exception object
});

service.put(path, argument, type) ⇒ Promise

Performs PUT requests with给定路径、数据和数据类型。

KindService
的实例方法 返回Promise - Promise 数据和响应对象

ParamTypeDefaultDescription
pathstringRequest path
argumentobjectData which will be sent (optional)
typestring&quot;application/vnd.oma.lwm2m+tlv&quot;Data type (optional)

service.delete(path) ⇒ Promise

使用给定路径执行 DELETE 请求。

KindService
的实例方法 返回Promise - Promise with data and response object

ParamTypeDescription
pathstringRequest path

service.post(path, argument, type) ⇒ Promise

使用给定的路径、数据和数据类型执行 POST 请求。

KindService
的实例方法 返回Promise - Promise with data and response object

ParamTypeDefaultDescription
pathstringRequest path
argumentobjectData which will be sent (optional)
typestring&quot;application/vnd.oma.lwm2m+tlv&quot;Data type (optional)

TYPE

表示 LwM2M 变量(标识符)类型(OBJECTINSTANCE, 多个资源、RESOURCE_INSTANCE、RESOURCE)。

种类:全局常量

RESOURCE_TYPE

表示资源类型(NONE、BOOLEAN、INTEGER、FLOAT、STRING、OPAQUE)。

种类:全局常量

getDictionaryByValue(dictionaryList, keyName, value) ⇒ Object | string | number

通过键和值的给定名称获取字典。

种类:全局函数
返回对象 | <代码>字符串 | number - 字典

ParamTypeDescription
dictionaryListobjectDictionary list.
keyNameObject | stringName of the key
valueObject | string | numberValue

encodeResourceValue(resource) ⇒ object

对资源值进行编码。

种类:全局函数
返回object - buffer - 编码值的缓冲区。

ParamTypeDescription
resourceobjectObject which stores resource value and value's type.

示例

const resource = {
 type: TLV.RESOURCE_TYPE.INTEGER,
 value: 1
};

const encodedValue = encodeResourceValue(resource);
// encodedValue = <Buffer 01>

decodeResourceValue(buffer, resource) ⇒ Object | string | number | boolean

解码资源的值。

种类:全局函数
返回对象 | <代码>字符串 | <代码>编号 | boolean - value - 指定类型的解码值

ParamTypeDescription
bufferobjectBuffer which will be decoded.
resourceobjectObject which stores resource value's type.

Example

const buffer = Buffer.from([0x01]);
const resource = {
  type: TLV.RESOURCE_TYPE.INTEGER,
};

const decodedValue = decodeResourceValue(buffer, resource);
// decodedValue = 1

encode(object) ⇒ object

编码 ant 类型的实例(对象实例,多个资源,资源实例, 资源)。

种类:全局函数
返回object - 缓冲区 - 编码的 TLV 缓冲区。

ParamTypeDescription
objectobjectobject which stores type, identifier and value.

示例

const resource = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: true
};

const encoded = encode({
  type: TYPE.RESOURCE,
  identifier: resource.identifier,
  value: encodeResourceValue(resource),
});
// encoded = <Buffer e1 16 da 01>

encodeResourceInstance(resourceInstance) ⇒ object

将资源实例编码到 TLV 缓冲区。

种类:全局函数
返回object - buffer - TLV 格式的缓冲区

ParamTypeDescription
resourceInstanceobjectObject which stores resource identifier, value and it's type.

Example

const resourceInstance = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: true
};

const encoded = encodeResourceInstance(resourceInstance);
// encoded = <Buffer e1 16 da 01>

encodeMultipleResourcesTLV(resources) ⇒ object

将多个资源值编码为 TLV缓冲。

种类:全局函数
返回对象 - 缓冲区 - TLV 缓冲区。

ParamTypeDescription
resourcesobjectObject which stores identifier, resource type, and multiple values.

示例

const resources = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: [true, false]
};

const encoded = encodeMultipleResources(resources);
// encoded = <Buffer a6 16 da 41 00 01 41 01 00>

encodeResource(resource) ⇒ object

将资源编码到 TLV 缓冲区。

种类:全局函数
返回对象 - 缓冲区 - TLV 缓冲区。

ParamTypeDescription
resourceobjectObject which stores resource identifier, type and value.

示例

const resource = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: true
};

const encoded = encodeResourcez(resource);
// encoded = <Buffer e1 16 da 01>

encodeObjectInstance(objectInstance) ⇒ object

将 LwM2M 对象实例编码到 TLV 缓冲区。

种类:全局函数
返回对象 - 缓冲区 - TLV 缓冲区。

ParamTypeDescription
objectInstanceobjectLwM2M object.

示例

const objectInstance = {
  identifier: 0,
  resources: [
    {
      identifier: 5815,
      type: TLV.RESOURCE_TYPE.FLOAT,
      value: 999.99
    }
  ]
};

const encoded = encodeObjectInstanceTLV(objectInstance);
// encoded = <Buffer 07 00 e4 16 b7 44 79 ff 5c>

encodeObject(object) ⇒ object

将 LwM2M 对象编码到 TLV 缓冲区。

种类:全局函数
返回对象 - 缓冲区 - TLV 缓冲区。

ParamTypeDescription
objectobjectLwM2M object.

示例

const object = {
  identifier: 3305,
  objectInstances: [{
    identifier: 0,
    resources: [
      {
        identifier: 5815,
        type: TLV.RESOURCE_TYPE.FLOAT,
        value: 999.99
      }
    ]
  }]
};

const encoded = encodeObject(object);
// encoded = <Buffer 07 00 e4 16 b7 44 79 ff 5c>

decode(buffer) ⇒ object

解码任何 TLV 缓冲区。

种类:全局函数
返回object - object - 解码后的对象。

ParamTypeDescription
bufferobjectencoded TLV buffer.

示例

const buffer = Buffer.from([0xe1, 0x16, 0xda, 0x01]);

const decoded = TLV.decode(buffer);
// decoded = { type: 3, identifier: 5850, value: <Buffer 01>, tlvSize: 4 }

decodeResourceInstance(buffer, resources) ⇒ object

解码资源实例。

种类:全局函数
返回object - decodedResource - 存储资源标识符的对象, tlvSize 资源类型和值。

ParamTypeDescription
bufferobjectResource instance TLV buffer.
resourcesobjectObject which stores resource identifier and resource type.

示例

const buffer = Buffer.from([0x61, 0x16, 0xda, 0x01]);
const resources = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
};

const decoded = decodeResourceInstance(buffer, resources);
// decoded = { identifier: 5850, tlvSize: 4, type: TLV.RESOURCE_TYPE.BOOLEAN, value: true }

decodeResourceInstanceValue(buffer, resourceInstance) ⇒ object

解码资源实例值

种类:全局函数
返回object - decodedResourceValue - 解码后的资源值

ParamTypeDescription
bufferobjectResource instance value TLV buffer
resourceInstanceobjectObject which stores resource type

Example

const buffer = Buffer.from([0x01]);
const resourceInstance = {
  type: TLV.RESOURCE_TYPE.INTEGER,
};

const decoded = decodeResourceInstance(buffer, resources);
// decoded = 1

decodeResource(buffer, resource) ⇒ object

解码资源。

种类:全局函数
返回object - 缓冲区 - 解码后的资源。

ParamTypeDescription
bufferobjectResource TLV buffer
resourceobjectObject which stores identifier and resource type.

示例

const buffer = Buffer.from([0xe1, 0x16, 0xda, 0x01]);
const resource = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
};

const decoded = decodeResource(buffer, resource);
// decoded = { identifier: 5850, type: 1, value: true, tlvSize: 4 }

decodeObjectInstance(buffer, objectInstance) ⇒ object

从 TLV 缓冲区解码对象实例。

种类:全局函数
返回object - object - 解码后的对象实例。

ParamTypeDescription
bufferobjectTLV buffer.
objectInstanceobjectObject which stores object instance identifier and resources.

示例

const buffer = Buffer.from([0x07, 0x00, 0xe4, 0x16, 0xb7, 0x44, 0x79, 0xff, 0x5c]);
const objectInstance: {
  identifier: 0,
  resources: [
    {
      identifier: 5815,
      type: TLV.RESOURCE_TYPE.FLOAT,
    },
  ]
};

const decoded = decodeObjectInstance(buffer, objectInstance);
// decoded = { identifier: 0, resources: [ { identifier: 5815, type: 3 } ] }

decodeObject(buffer, object) ⇒ object

将 LwM2M 对象解码到 TLV 缓冲区。

种类:全局函数
返回object - object - 解码后的对象。

ParamTypeDescription
bufferobjectTLV buffer.
objectobjectObject which stores object instances with their resources.

例子

const buffer = Buffer.from([0x07, 0x00, 0xe4, 0x16, 0xb7, 0x44, 0x79, 0xff, 0x5c]);
const object = {
  identifier: 3305,
  objectInstances: [{
    identifier: 0,
    resources: [
      {
        identifier: 5815,
        type: TLV.RESOURCE_TYPE.FLOAT,
      },
    ]
  }]
};

const decoded = decodeObject(buffer, object);
/*
decoded = {
  identifier: 3305,
  objectInstances: [
    {
      identifier: 0,
      resources: [
        {
          identifier: 5815,
          type: 3,
          value: 999.989990234375,
          tlvSize: 7
        }
      ]
    }
  ]
}
*/

Build Statuscodecov

restserver-api

Example program This example shows basic restserver-api usage.

const restAPI = require('restserver-api');

const { Lwm2m } = restAPI;
const { RESOURCE_TYPE, encodeResource, decodeResource } = Lwm2m.TLV;

console.log('Initialize service and endpoint');
const service = new restAPI.Service();
const device = new restAPI.Device(service, 'urn:uuid:17200d69-ec9b-43b3-9051-73df2207907c');

console.log('Encode resource to TLV format');
const tlvBuffer = encodeResource({
  identifier: 3,
  type: RESOURCE_TYPE.INTEGER,
  value: 60
});

console.log('Start service');
service.start().then(() => {
  console.log('Service started');
  console.log('Writing into device\'s resource');
  device.write('/3/0/7', (status) => {
    console.log('Received response with status: ', status);
    console.log('Stopping service');
    service.stop().then(() => {
      console.log('Service stopped');
    });
  }, tlvBuffer);
});

Classes

Device

This class represents device (endpoint).

Service

This class represents REST API service.

Constants

TYPE

Represents LwM2M variable (identifier) types (OBJECT_INSTANCE, MULTIPLE_RESOURCE, RESOURCE_INSTANCE, RESOURCE).

RESOURCE_TYPE

Represents resource type (NONE, BOOLEAN, INTEGER, FLOAT, STRING, OPAQUE).

Functions

getDictionaryByValue(dictionaryList, keyName, value)Object | string | number

Gets dictionary by given name of the key and value.

encodeResourceValue(resource)object

Encodes value of the resource.

decodeResourceValue(buffer, resource)Object | string | number | boolean

Decodes value of the resource.

encode(object)object

Encodes ant type of instance (Object instance, multiple resources, resources instance, resource).

encodeResourceInstance(resourceInstance)object

Encodes resource instance to TLV buffer.

encodeMultipleResourcesTLV(resources)object

Encodes multiple resource values to TLV buffer.

encodeResource(resource)object

Encodes resource to TLV buffer.

encodeObjectInstance(objectInstance)object

Encodes LwM2M object instance to TLV buffer.

encodeObject(object)object

Encodes LwM2M object to TLV buffer.

decode(buffer)object

Decodes any TLV buffer.

decodeResourceInstance(buffer, resources)object

Decodes resource instance.

decodeResourceInstanceValue(buffer, resourceInstance)object

Decodes resource instance value

decodeResource(buffer, resource)object

Decodes resource.

decodeObjectInstance(buffer, objectInstance)object

Decodes object instance from TLV buffer.

decodeObject(buffer, object)object

Decodes LwM2M object to TLV buffer.

Device

This class represents device (endpoint).

Kind: global class

new Device(service, id)

Constructor initiliazes given service object, device's id and starts listening for events emited by service (when device registers, updates, deregisters, sends data), handles "async responses" and emits "register", "update", "deregister" events.

ParamTypeDescription
serviceobjectService object
idstringEndpoint id

Example

const restAPI = require('restserver-api');

const service = new restAPI.Service(serviceOptions);
const device = new restAPI.Device(service, 'deviceId');

device.getObjects() ⇒ Promise

Sends request to get all device's objects.

Kind: instance method of Device
Returns: Promise - Promise object with device's objects
Example

device.getObjects().then((resp) => {
  // resp = [ { uri: '/1/0' }, { uri: '/2/0' }, ... ]
}).catch((err) => {
  // err - exception message object or status code
});

device.read(path, callback) ⇒ Promise

Sends request to read device's resource data.

Kind: instance method of Device
Returns: Promise - Promise with async response id

ParamTypeDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received

Example

device.read(path, (status, payload) => {
  // status = 200
  // payload = 4RbaAA==
}).then((asyncResponseId) => {
  // asyncResponseId = 1533889157#42f26784-1a8d-4861-36aa-d88f
}).catch((err) => {
  // err - exception object or status code
});

device.write(path, callback, payload, type) ⇒ Promise

Sends request to write a value into device's resource.

Kind: instance method of Device
Returns: Promise - Promise with async response id

ParamTypeDefaultDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received
payloadbufferData (optional)
typestring&quot;application/vnd.oma.lwm2m+tlv&quot;Content type (optional)

Example

device.write(path, (status) => {
  // status = 202
}, payload).then((asyncResponseId) => {
  // asyncResponseId = 1533889926#870a3f17-3e21-b6ad-f63d-5cfe
}).catch((err) => {
  // err - exception object or status code
});

device.execute(path, callback, payload, type) ⇒ Promise

Sends request to execute device's resource.

Kind: instance method of Device
Returns: Promise - Promise with async response id

ParamTypeDefaultDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received
payloadbufferData (optional)
typestring&quot;text/plain&quot;Content type (optional)

Example

device.execute(path, (status) => {
  // status = 202
}).then((asyncResponseId) => {
  // asyncResponseId = 1533889926#870a3f17-3e21-b6ad-f63d-5cfe
}).catch((err) => {
  // err - exception object or status code
});

device.observe(path, callback) ⇒ Promise

Sends request to subscribe to resource.

Kind: instance method of Device
Returns: Promise - Promise with async response id

ParamTypeDescription
pathstringResource path
callbackfunctionCallback which will be called when async response is received

Example

device.observe(path, (status, payload) => {
  // status = 200
  // payload = 4RbaAA==
}).then((asyncResponseId) => {
  // asyncResponseId = 1533889157#42f26784-1a8d-4861-36aa-d88f
}).catch((err) => {
  // err - exception object or status code
});

device.cancelObserve(path) ⇒ Promise

Sends request to cancel subscriptions.

Kind: instance method of Device
Returns: Promise - Promise with HTTP status code

ParamTypeDescription
pathstringResource path

Example

device.cancelObserve(path).then((status) => {
  // status - status code
}).catch((err) => {
  // err - exception object
});

Service

This class represents REST API service.

Kind: global class

new Service(opts)

Initializes default configurations. Reconfigures with given options.

ParamTypeDescription
optsobjectOptions object (optional)

Example

const options = {
  // REST server's address
  host: 'http://localhost:8888',
  // CA certificate
  ca: '',
  // authentication (true or false)
  authentication: false,
  username: '',
  password: '',
  // notification polling (true or false)
  polling: false,
  // time between each poll in miliseconds
  interval: 1234,
  // port for socket listener (not relevant if polling is enabled)
  port: 5728,
};
new Service(options);

service.start(opts) ⇒ Promise

(Re)starts authentication, socket listener creation and notification callback registration or notification polling processes.

Kind: instance method of Service
Returns: Promise - Promise which fulfills when service is started

ParamTypeDescription
optsobjectOptions object (optional)

Example

service.start().then(() => {
  // started service
}).catch((err) => {
  // err - exception object
});

Example (Passing options object)

const options = {
  // REST server's address
  host: 'http://localhost:8888',
  // CA certificate
  ca: '',
  // authentication (true or false)
  authentication: false,
  username: '',
  password: '',
  // notification polling (true or false)
  polling: false,
  // time between each poll in miliseconds
  interval: 1234,
  // port for socket listener (not relevant if polling is enabled)
  port: 5728,
};
service.start(options);

service.stop() ⇒ Promise

Stops receiving and processing events Stops this service and all it's subservices that were started in start(). Cleans up resources

Kind: instance method of Service
Returns: Promise - Promise which fulfills when service is stopped
Example

service.stop().then(() => {
  // stopped service
});

service.authenticate() ⇒ Promise

Sends request to authenticate user.

Kind: instance method of Service
Returns: Promise - Promise with authentication data (token and after what time it expires)
Example

service.authenticate().then((resp) => {
  // resp = { access_token: 'token-value', expires_in: 3600 }
}).catch((err) => {
  // err - exception message object or status code
});

service.registerNotificationCallback() ⇒ Promise

Sends request to register notification callback.

Kind: instance method of Service
Returns: Promise - Promise which fulfills when notification callback is registered
Example

service.registerNotificationCallback().then(() => {
  // notification callback has been registered
}).catch((err) => {
  // err - exception object or status code
});

service.deleteNotificationCallback() ⇒ Promise

Sends request to delete notification callback.

Kind: instance method of Service
Returns: Promise - Promise with HTTP status code
Example

service.deleteNotificationCallback().then((status) => {
  // status - status code
}).catch((err) => {
  // err - exception object
});

service.checkNotificationCallback() ⇒ Promise

Sends request to check whether or not notification callback is registered.

Kind: instance method of Service
Returns: Promise - Promise with notification callback data
Example

service.checkNotificationCallback().then((resp) => {
  // resp = { url: 'http://localhost:5728/notification', headers: {} }
}).catch((err) => {
  // err - exception message object or status code
});

service.pullNotification() ⇒ Promise

Sends request to get pending/queued notifications.

Kind: instance method of Service
Returns: Promise - Promise with notification data (registrations, deregistrations, updates, async responses)
Example

service.pullNotification().then((resp) => {
  // resp = { registrations: [...], 'reg-updates': [...], ... }
}).catch((err) => {
  // err - exception object
});

service.getDevices() ⇒ Promise

Sends request to get all registered endpoints.

Kind: instance method of Service
Returns: Promise - Promise with a list of endpoints
Example

service.getDevices().then((resp) => {
  // resp = [ { name: 'uuid-4567', type: '8dev_3700', ... }, ... ]
}).catch((err) => {
  // err - exception message object or status code
});

service.getVersion() ⇒ Promise

Sends request to get REST server version.

Kind: instance method of Service
Returns: Promise - Promise with REST server's version
Example

service.getVersion().then((resp) => {
  // resp = '1.0.0'
}).catch((err) => {
  // err - exception object
});

service.get(path) ⇒ Promise

Performs GET requests with given path.

Kind: instance method of Service
Returns: Promise - Promise with data and response object

ParamTypeDescription
pathstringRequest path

Example

service.get(path).then((dataAndResponse) => {
  // dataAndResponse.data - data object
  // dataAndResponse.resp - response object
}).catch((err) => {
  // err - exception object
});

service.put(path, argument, type) ⇒ Promise

Performs PUT requests with given path, data and data type.

Kind: instance method of Service
Returns: Promise - Promise with data and response object

ParamTypeDefaultDescription
pathstringRequest path
argumentobjectData which will be sent (optional)
typestring&quot;application/vnd.oma.lwm2m+tlv&quot;Data type (optional)

service.delete(path) ⇒ Promise

Performs DELETE requests with given path.

Kind: instance method of Service
Returns: Promise - Promise with data and response object

ParamTypeDescription
pathstringRequest path

service.post(path, argument, type) ⇒ Promise

Performs POST requests with given path, data and data type.

Kind: instance method of Service
Returns: Promise - Promise with data and response object

ParamTypeDefaultDescription
pathstringRequest path
argumentobjectData which will be sent (optional)
typestring&quot;application/vnd.oma.lwm2m+tlv&quot;Data type (optional)

TYPE

Represents LwM2M variable (identifier) types (OBJECTINSTANCE, MULTIPLERESOURCE, RESOURCE_INSTANCE, RESOURCE).

Kind: global constant

RESOURCE_TYPE

Represents resource type (NONE, BOOLEAN, INTEGER, FLOAT, STRING, OPAQUE).

Kind: global constant

getDictionaryByValue(dictionaryList, keyName, value) ⇒ Object | string | number

Gets dictionary by given name of the key and value.

Kind: global function
Returns: Object | string | number - dictionary

ParamTypeDescription
dictionaryListobjectDictionary list.
keyNameObject | stringName of the key
valueObject | string | numberValue

encodeResourceValue(resource) ⇒ object

Encodes value of the resource.

Kind: global function
Returns: object - buffer - Buffer of encoded value.

ParamTypeDescription
resourceobjectObject which stores resource value and value's type.

Example

const resource = {
 type: TLV.RESOURCE_TYPE.INTEGER,
 value: 1
};

const encodedValue = encodeResourceValue(resource);
// encodedValue = <Buffer 01>

decodeResourceValue(buffer, resource) ⇒ Object | string | number | boolean

Decodes value of the resource.

Kind: global function
Returns: Object | string | number | boolean - value - Decoded value in specified type

ParamTypeDescription
bufferobjectBuffer which will be decoded.
resourceobjectObject which stores resource value's type.

Example

const buffer = Buffer.from([0x01]);
const resource = {
  type: TLV.RESOURCE_TYPE.INTEGER,
};

const decodedValue = decodeResourceValue(buffer, resource);
// decodedValue = 1

encode(object) ⇒ object

Encodes ant type of instance (Object instance, multiple resources, resources instance, resource).

Kind: global function
Returns: object - buffer - encoded TLV buffer.

ParamTypeDescription
objectobjectobject which stores type, identifier and value.

Example

const resource = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: true
};

const encoded = encode({
  type: TYPE.RESOURCE,
  identifier: resource.identifier,
  value: encodeResourceValue(resource),
});
// encoded = <Buffer e1 16 da 01>

encodeResourceInstance(resourceInstance) ⇒ object

Encodes resource instance to TLV buffer.

Kind: global function
Returns: object - buffer - Buffer in TLV format

ParamTypeDescription
resourceInstanceobjectObject which stores resource identifier, value and it's type.

Example

const resourceInstance = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: true
};

const encoded = encodeResourceInstance(resourceInstance);
// encoded = <Buffer e1 16 da 01>

encodeMultipleResourcesTLV(resources) ⇒ object

Encodes multiple resource values to TLV buffer.

Kind: global function
Returns: object - buffer - TLV buffer.

ParamTypeDescription
resourcesobjectObject which stores identifier, resource type, and multiple values.

Example

const resources = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: [true, false]
};

const encoded = encodeMultipleResources(resources);
// encoded = <Buffer a6 16 da 41 00 01 41 01 00>

encodeResource(resource) ⇒ object

Encodes resource to TLV buffer.

Kind: global function
Returns: object - buffer - TLV buffer.

ParamTypeDescription
resourceobjectObject which stores resource identifier, type and value.

Example

const resource = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
  value: true
};

const encoded = encodeResourcez(resource);
// encoded = <Buffer e1 16 da 01>

encodeObjectInstance(objectInstance) ⇒ object

Encodes LwM2M object instance to TLV buffer.

Kind: global function
Returns: object - buffer - TLV buffer.

ParamTypeDescription
objectInstanceobjectLwM2M object.

Example

const objectInstance = {
  identifier: 0,
  resources: [
    {
      identifier: 5815,
      type: TLV.RESOURCE_TYPE.FLOAT,
      value: 999.99
    }
  ]
};

const encoded = encodeObjectInstanceTLV(objectInstance);
// encoded = <Buffer 07 00 e4 16 b7 44 79 ff 5c>

encodeObject(object) ⇒ object

Encodes LwM2M object to TLV buffer.

Kind: global function
Returns: object - buffer - TLV buffer.

ParamTypeDescription
objectobjectLwM2M object.

Example

const object = {
  identifier: 3305,
  objectInstances: [{
    identifier: 0,
    resources: [
      {
        identifier: 5815,
        type: TLV.RESOURCE_TYPE.FLOAT,
        value: 999.99
      }
    ]
  }]
};

const encoded = encodeObject(object);
// encoded = <Buffer 07 00 e4 16 b7 44 79 ff 5c>

decode(buffer) ⇒ object

Decodes any TLV buffer.

Kind: global function
Returns: object - object - Decoded object.

ParamTypeDescription
bufferobjectencoded TLV buffer.

Example

const buffer = Buffer.from([0xe1, 0x16, 0xda, 0x01]);

const decoded = TLV.decode(buffer);
// decoded = { type: 3, identifier: 5850, value: <Buffer 01>, tlvSize: 4 }

decodeResourceInstance(buffer, resources) ⇒ object

Decodes resource instance.

Kind: global function
Returns: object - decodedResource - Object which stores resource identifier, tlvSize resource type and value.

ParamTypeDescription
bufferobjectResource instance TLV buffer.
resourcesobjectObject which stores resource identifier and resource type.

Example

const buffer = Buffer.from([0x61, 0x16, 0xda, 0x01]);
const resources = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
};

const decoded = decodeResourceInstance(buffer, resources);
// decoded = { identifier: 5850, tlvSize: 4, type: TLV.RESOURCE_TYPE.BOOLEAN, value: true }

decodeResourceInstanceValue(buffer, resourceInstance) ⇒ object

Decodes resource instance value

Kind: global function
Returns: object - decodedResourceValue - Decoded resource value

ParamTypeDescription
bufferobjectResource instance value TLV buffer
resourceInstanceobjectObject which stores resource type

Example

const buffer = Buffer.from([0x01]);
const resourceInstance = {
  type: TLV.RESOURCE_TYPE.INTEGER,
};

const decoded = decodeResourceInstance(buffer, resources);
// decoded = 1

decodeResource(buffer, resource) ⇒ object

Decodes resource.

Kind: global function
Returns: object - buffer - Decoded resource.

ParamTypeDescription
bufferobjectResource TLV buffer
resourceobjectObject which stores identifier and resource type.

Example

const buffer = Buffer.from([0xe1, 0x16, 0xda, 0x01]);
const resource = {
  identifier: 5850,
  type: TLV.RESOURCE_TYPE.BOOLEAN,
};

const decoded = decodeResource(buffer, resource);
// decoded = { identifier: 5850, type: 1, value: true, tlvSize: 4 }

decodeObjectInstance(buffer, objectInstance) ⇒ object

Decodes object instance from TLV buffer.

Kind: global function
Returns: object - object - Decoded object instance.

ParamTypeDescription
bufferobjectTLV buffer.
objectInstanceobjectObject which stores object instance identifier and resources.

Example

const buffer = Buffer.from([0x07, 0x00, 0xe4, 0x16, 0xb7, 0x44, 0x79, 0xff, 0x5c]);
const objectInstance: {
  identifier: 0,
  resources: [
    {
      identifier: 5815,
      type: TLV.RESOURCE_TYPE.FLOAT,
    },
  ]
};

const decoded = decodeObjectInstance(buffer, objectInstance);
// decoded = { identifier: 0, resources: [ { identifier: 5815, type: 3 } ] }

decodeObject(buffer, object) ⇒ object

Decodes LwM2M object to TLV buffer.

Kind: global function
Returns: object - object - Decoded object.

ParamTypeDescription
bufferobjectTLV buffer.
objectobjectObject which stores object instances with their resources.

Example

const buffer = Buffer.from([0x07, 0x00, 0xe4, 0x16, 0xb7, 0x44, 0x79, 0xff, 0x5c]);
const object = {
  identifier: 3305,
  objectInstances: [{
    identifier: 0,
    resources: [
      {
        identifier: 5815,
        type: TLV.RESOURCE_TYPE.FLOAT,
      },
    ]
  }]
};

const decoded = decodeObject(buffer, object);
/*
decoded = {
  identifier: 3305,
  objectInstances: [
    {
      identifier: 0,
      resources: [
        {
          identifier: 5815,
          type: 3,
          value: 999.989990234375,
          tlvSize: 7
        }
      ]
    }
  ]
}
*/
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文