How to Manage Control Instructions for Offline Devices through Device Shadow

Image for post
Image for post

Updating the Running Parameters of Offline IoT-enabled Devices Through Device Shadow

1) Technical Solution for Updating the Running Parameters of Devices

Image for post
Image for post

2) Device-side Development

/**
* aliyun-iot-mqtt@0.0.4
*/
const mqtt = require('aliyun-iot-mqtt');
//设备身份三元组+区域
const deviceConfig = {
"productKey": "产品",
"deviceName": "设备",
"deviceSecret": "设备deviceSecret",
"regionId": "cn-shanghai"
};
//1.建立连接
const client = mqtt.getAliyunIotMqttClient(deviceConfig);
//2.订阅设备影子topic
const getShadow = `/shadow/get/${deviceConfig.productKey}/${deviceConfig.deviceName}`;
client.subscribe(getShadow)
client.on('message', function(topic, message) {
//收到消息后,显示设备影子中的远程配置参数
if (topic == getShadow) {
message = JSON.parse(message);
console.log(new Date().Format("yyyy-MM-dd HH:mm:ss.S"))
console.log("\tappConfig.content :", JSON.stringify(message.payload.state.desired.appConfig))
console.log("\tappConfig.timestamp :", JSON.stringify(message.payload.metadata.desired.appConfig.timestamp))
}
})
//3.主动获取设备影子中的远程配置参数
const updateShadow = `/shadow/update/${deviceConfig.productKey}/${deviceConfig.deviceName}`;
client.publish(updateShadow, JSON.stringify({method: "get"}), { qos: 1 })

3) Configuration Update on the Cloud

/**
* package.json 添加依赖:"@alicloud/pop-core": "1.5.2"
*/
const co = require('co');
const RPCClient = require('@alicloud/pop-core').RPCClient;
const options = {
accessKey: "你的accessKey",
accessKeySecret: "你的accessKeySecret",
};
//1.初始化client
const client = new RPCClient({
accessKeyId: options.accessKey,
secretAccessKey: options.accessKeySecret,
endpoint: 'https://iot.cn-shanghai.aliyuncs.com',
apiVersion: '2018-01-20'
});
//2.desired中appConfig变更
const shadowMessage = {
method: "update",
state: {
desired: {
appConfig:{
maxTemperature: 39.5,
}
}
},
version: Date.now()
}
const params = {
ProductKey: "你的ProductKey",
DeviceName: "你的DeviceName",
ShadowMessage: JSON.stringify(shadowMessage)
};
co(function*() {
try {
//3.发起API调用,更新影子中配置参数
const response = yield client.request('UpdateDeviceShadow', params);
console.log(JSON.stringify(response));
} catch (err) {
console.log(err);
}
});

4) Running Results

4.1 Update Parameter Settings Through an API on the Cloud

Image for post
Image for post

4.2 Obtain Live Updates on Online Devices

Image for post
Image for post

4.3 Obtain Updates After Devices Go Online

Image for post
Image for post

Original Source:

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store