[指令下行]通过IoT物联网平台发送指令控制设备
本教程演示如何通过IoT物联网平台下行控制指令。<br />
我们以微信小程序作为模拟设备,设备上线后,点击订阅主题,会默认订阅主题为 /{deviceName}/user/get 的指令,然后业务系统调用POP API发送指令到IoT平台,IoT平台把指令推送到设备端。
1.小程序模拟设备
1.1 创建高级版产品
** 高级版,JSON格式**<br />1.2 指令下行Topic查看
1.3 注册设备
在产品下注册设备,获得身份三元组<br />2.通过POP API发送控制指令(Nodejs版)
2.1 依赖pop sdk
"@alicloud/pop-core": "1.5.2",
"co": "4.6.0"
2.2 发送指令代码
POP API https://help.aliyun.com/document_detail/69793.html
const co = require('co');
const RPCClient = require('@alicloud/pop-core').RPCClient;
const deviceInfo = {
productKey: '接收指令的设备productKey',
deviceName: '接收指令的设备deviceName'
}
const options = {
accessKey: "云账号accessKey",
accessKeySecret: "云账号accessKeySecret",
};
//1.创建client
const client = new RPCClient({
accessKeyId: options.accessKey,
secretAccessKey: options.accessKeySecret,
endpoint: options.endpoint || 'https://iot.cn-shanghai.aliyuncs.com',
apiVersion: options.apiVersion || '2018-01-20'
});
co(function*() {
try {
const pubBody = { msg: "这是来自云端的指令" }
// 2.构造iot API
// 这里是POP API的Action
const action = 'Pub';
// 这里是POP API的入参params
const params = {
ProductKey: deviceInfo.productKey,
TopicFullName: `/${deviceInfo.productKey}/${deviceInfo.deviceName}/user/get`,
MessageContent: new Buffer(JSON.stringify(pubBody)).toString('base64'),
Qos: 1
};
//2.发送请求
const response = yield client.request(action, params);
console.log('send command :'+JSON.stringify(pubBody));
console.log('\napi return :'+JSON.stringify(response));
} catch (err) {
console.log(err)
}
});