这一节我们开始实现 IotHub 指令下发的 DeviceSDK 端的功能。首先进行消息去重, 接着使用正则表达式提取出元数据, 然后通过事件的方式将指令的数据传递给设备应用代码, 最后提供一个接口供设备对指令进行回复。
消息去重
在本课程里面我们会使用 node-persist 来存储已收到指令的 RequestID。
首先初始化存储:
//IotHub_Device/sdk/iot_device.js
const storage = require('node-persist');
class IotDevice extends EventEmitter {
constructor({serverAddress = "127.0.0.1:8883", productName, deviceName, secret, clientID, storePath} = {}) {
...
storage.init({dir: `${storePath}/message_cache`})
...
}
然后实现检查指令是否重复的函数:
//IotHub_Device/sdk/iot_device.js
class IotDevice extends EventEmitter {
...
checkRequestDuplication(requestID, callback) {
var key = `requests/${requestID}`
storage.getItem(key, function (err, value) {
if (value ==