
在物联网场景中,常常会有全量设备消息广播诉求。如何把消息瞬间推送到海量在线设备上?
阿里云IoT企业物联网实例为开发者提供了 PubBroadcast 接口,可以在 秒级触达100万 在线设备,使得企业面在面对高并发需求时无后顾之忧。
我们以收款音箱场景消息广播为例,演示全量设备广播功能。


Topic示例:
/sys/g6palBDnzyT/dk004/broadcast/request/1386995865331441413
Payload示例:
{
"volume": 80,
"mode": 4
}
// node broadcast-device.js
const mqtt = require('aliyun-iot-mqtt');
//1.设备身份三元组+区域
const options = require("./iot-device-config.json");
// 2. 建立MQTT连接
const client = mqtt.getAliyunIotMqttClient(options);
//系统全量广播 Topic 前缀
const allBroadcastTopic = `/sys/${options.productKey}/${options.deviceName}/broadcast/request`;
client.on('message', function(topic, message) {
//过滤全量广播消息
if (topic.indexOf(allBroadcastTopic) > -1) {
console.log("设备收到全量广播消息:")
console.log("\ttopic=" + topic)
console.log("\tmessage=" + message)
}
})
iot-device-config.json 设备配置参数:
{
productKey: "g6palBDnzyT",
deviceName: "dk004",
deviceSecret: "424ed56661980c604255507d1b81464e",
host: "iot-060a08kg.mqtt.iothub.aliyuncs.com"
}
// node broadcast.js
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: '
apiVersion: '2018-01-20'
});
// 2.构造iot API
// 这里是POP API的Action
const action = 'PubBroadcast';
// 广播内容
const payload = {
volume: 80,
mode: 4
};
// 完整入参 params
const params = {
ProductKey: "g6palBDnzyT",
IotInstanceId: "iot-064a04kg",
MessageContent: new Buffer(JSON.stringify(payload)).toString("base64")
};
co(function*() {
//3.发起全量广播PubBroadcast API调用
try {
const response = yield client.request('PubBroadcast', params);
console.log("PubBroadcast 成功 =====>", JSON.stringify(response));
} catch (err) {
console.log("PubBroadcast 失败 =====>", JSON.stringify(err));
}
});
业务服务器调用 PubBroadcast API 日志:

4个设备端收到的广播消息日志:
Topic的消息id相同,deviceName不同

物联网平台产品介绍详情:

阿里云物联网平台客户交流群
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70017009/viewspace-2936785/ ,如需转载,请注明出处,否则将追究法律责任。