广播消息下发是阿里云物联网平台提供给云端应用向批量设备发送消息的一种机制, 本文讲解云端应用如何调用Broadcast接口将消息广播到设备,以及设备对广播消息进行处理。

例程讲解

说明 广播消息详情请参见Broadcast API说明
  1. 设备端开发

    默认地, 从云端下推的广播消息设备无需订阅topic就能收到。 如果业务上需要将广播的topic和自己的某个MQTT回调函数匹配, 那么使用以下topic即可。

    /sys/${product_key}/${device_name}/broadcast/request/+

    设备收到云端的广播消息后, 按自己业务进行处理即可。

    demos/mqtt_broadcast_demo.c所示, 在demo_mqtt_default_recv_handler中将简单打印收到的广播消息。

    ...
            case AIOT_MQTTRECV_PUB: {
                printf("pub, qos: %d, topic: %.*s\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
                printf("pub, payload: %.*s\n", packet->data.pub.payload_len, packet->data.pub.payload);
                /* TODO: 处理服务器下发的业务报文, 此处打印broadcast的报文 */
                /* 值得注意的是, 云端下发的广播topic格式为 /sys/${product_key}/${device_name}/broadcast/request/+ */
            }
            break;
    ...

    编译SDK, 运行./output/mqtt-broadcast-demo

    [1583135792.733][LK-0313] MQTT user calls aiot_mqtt_connect api, connect
    [1583135792.733][LK-0317] mqtt_broadcast_demo&a13FNXXXXXX
    [1583135792.733][LK-0318] 3FC4A3DED5AC5F31C4969CBB1868758B17FAB2E5070FC51C98809104725500E3
    [1583135792.733][LK-0319] a13FNXXXXXX.mqtt_broadcast_demo|timestamp=2524608000000,_ss=1,_v=sdk-c-4.0.0,securemode=2,signmethod=hmacsha256,ext=1,|
    establish mbedtls connection with server(host='a13FNXXXXXX.iot-as-mqtt.cn-shanghai.aliyuncs.com', port=[443])
    success to establish mbedtls connection, fd = 6(cost 44763 bytes in total, max used 47675 bytes)
    [1583135792.888][LK-0313] MQTT connect success in 147 ms
    AIOT_MQTTEVT_CONNECT
    heartbeat response
    ...
  2. 调用云端SDK向设备发送广播报文

    云端SDK参考

    使用云端SDK调用Broadcast

    这里为了配合设备端进行演示, 云端SDK调用代码如下:

    PubBroadcastRequest request = new PubBroadcastRequest();
    request.setProductKey("a13FNXXXXXX");
    request.setMessageContent(Base64.getEncoder().encodeToString("receive broadcast from cloud".getBytes()));
    PubBroadcastResponse response = client.getAcsResponse(request);
    System.out.println("PubBroadcastResponse\n" + new Gson().toJson(response) + "\n");

    调用完成后, 云端SDK日志如下:

    {"requestId":"642A8CAB-6205-4F50-9E03-5F56947B52D4","success":true}

    调用完成后, 设备端日志如下:

    [1583135985.622][LK-0309] pub: /sys/a13FNXXXXXX/mqtt_broadcast_demo/broadcast/request/1234387906840325632
    [LK-030A] < 72 65 63 65 69 76 65 20  62 72 6F 61 64 63 61 73 | receive broadcas
    [LK-030A] < 74 20 66 72 6F 6D 20 63  6C 6F 75 64             | t from cloud
    pub, qos: 0, topic: /sys/a13FNXXXXXX/mqtt_broadcast_demo/broadcast/request/1234387906840325632
    pub, payload: receive broadcast from cloud

    从上面云端和设备端的日志可以看出, 设备端收到了云端的一条广播消息receive broadcast from cloud. 至此, Broadcast功能调用完成。

常见错误

广播消息发送过快, 被云端限流. 建议广播发送频率不要超过每分钟1次。

{
    "requestId":"61AD9495-6A88-4B88-BB62-8E1F235C44A9",
    "success":false,
    "code":"iot。messagebroker。RateLimit"
}