Broadcast communication

更新时间:
复制 MD 格式

IoT Platform supports broadcast communication, which allows you to send a message to all devices of a specified product, or to all devices that subscribe to a specific topic. Broadcast messages from your business server are received only by online devices. This topic provides an example of how to broadcast a message to all online devices.

Background information

  • Broadcast a message to all online devices of a product

    Your business server calls the PubBroadcast API operation and passes the ProductKey of the target product and the MessageContent. All online devices of the product receive the MessageContent on the broadcast topic /sys/${productKey}/${deviceName}/broadcast/request/${MessageId}.

    The MessageId in the broadcast topic is an ID generated by IoT Platform. After the message is successfully sent, IoT Platform returns this ID to your business server as part of the response from the PubBroadcast call.

    For example, a manufacturer with multiple smart locks connected to IoT Platform can use a business server to send a single command to all online locks to invalidate a specific password.

    广播通信
  • Broadcast a message to all devices that subscribe to a specific topic

    Devices subscribe to the same broadcast topic. Your business server calls the PubBroadcast API operation, passing the ProductKey, MessageContent, and the full name of the broadcast topic. The topic name must be in the format /broadcast/${productKey}/custom-field. All online devices that are subscribed to this topic receive the MessageContent.

    Important
    • Broadcast topics are defined in the device-side code during development. You do not need to create them in the IoT Platform console.
    • A maximum of 1,000 devices can subscribe to a single broadcast topic. If you have more devices, you must segment them into groups. For example, to broadcast to 5,000 devices, you can divide them into five groups of 1,000. You must then call the PubBroadcast operation five times, setting the custom field to group1, group2, group3, group4, and group5 respectively. Each group of devices must subscribe to its corresponding topic.

    For more information about the broadcast API operation, see PubBroadcast.

Limits

  • Broadcast messages are sent only to online devices within a product.
  • When you broadcast messages to specific online devices by topic subscription, the maximum call frequency for the broadcast API is once per second.
  • When you broadcast messages to all online devices of a product, the devices do not need to subscribe to a broadcast topic. The maximum call frequency for the broadcast API is once per minute.
  • The maximum size of a broadcast message body is 64 KB.
Important Broadcast messages are not subject to the data forwarding Transactions Per Second (TPS) limit of your instance. For example, if your instance has a TPS limit of 100 for data forwarding and you have 500 online devices, a broadcast call delivers the message to all 500 devices, not just 100.

Prepare the development environment

This example uses Java SDKs for both the device and the server. You must prepare a Java development environment. Download and install the Java Development Kit (JDK) from the official Java website.

Add Maven dependencies

Create a project and add the following Maven dependencies to the pom.xml file.

Note The IoT Java SDK versions in the following code are for reference only. For the latest dependency information, go to the page.
<dependencies>
  <dependency>
     <groupId>com.aliyun.alink.linksdk</groupId>
     <artifactId>iot-linkkit-java</artifactId>
     <version>1.2.0.1</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>aliyun-java-sdk-core</artifactId>
      <version>4.5.6</version>
  </dependency>
  <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>aliyun-java-sdk-iot</artifactId>
      <version>7.41.0</version>
  </dependency>
  <dependency>
    <groupId>com.aliyun.openservices</groupId>
    <artifactId>iot-client-message</artifactId>
    <version>1.1.2</version>
  </dependency>
</dependencies>

Create a product and devices

  1. Log on to the IoT Platform console.
  2. On the Overview page, find the instance that you want to manage and click the instance ID or instance name.

  3. In the left-side navigation pane, choose Device Management > Products.
  4. Click Create Product to create a Smart Lock product. For more information, see Create a product.
  5. In the left-side navigation pane, choose Device Management > Devices, and then create three devices for the Smart Lock product. For more information, see Create multiple devices at a time.

Configure the device SDK

  • Connect your devices to IoT Platform.
    • Configure the device credentials.
      final String productKey = "<yourProductKey>";
      final String deviceName = "<yourDeviceName>";
      final String deviceSecret = "<yourDeviceSecret>";
      final String region = "<yourRegionID>";

      The productKey, deviceName, and deviceSecret are your device credentials. To obtain them, go to the IoT Platform console, navigate to your instance, and choose Device Management > Devices. Find the device and click View to go to the Device Details page.

      The region parameter specifies the device's region. For information about how to specify a region, see Regions and zones.

    • Set the initialization parameters, including MQTT settings, device information, and initial device status.
      LinkKitInitParams params = new LinkKitInitParams();
      // LinkKit uses MQTT as its underlying protocol. Configure the MQTT settings.
      IoTMqttClientConfig config = new IoTMqttClientConfig();
      config.productKey = productKey;
      config.deviceName = deviceName;
      config.deviceSecret = deviceSecret;
      config.channelHost = productKey + ".iot-as-mqtt." + region + ".aliyuncs.com:1883";
      // Specify the device information.
      DeviceInfo deviceInfo = new DeviceInfo();
      deviceInfo.productKey = productKey;
      deviceInfo.deviceName = deviceName;
      deviceInfo.deviceSecret = deviceSecret;
      // Specify the initial status of the device.
      Map<String, ValueWrapper> propertyValues = new HashMap<String, ValueWrapper>();
      params.mqttClientConfig = config;
      params.deviceInfo = deviceInfo;
      params.propertyValues = propertyValues;

      The channelHost is the MQTT endpoint. To obtain endpoints for public and Enterprise Edition instances, see View and configure instance endpoints.

    • Initialize the connection.
      // Establish the connection and set a listener for the connection result.
      LinkKit.getInstance().init(params, new ILinkKitConnectListener() {
           @Override
           public void onError(AError aError) {
               System.out.println("Init error:" + aError);
           }
           // The callback that is invoked after the initialization is complete.
           @Override
           public void onInitDone(InitResult initResult) {
               System.out.println("Init done:" + initResult);
           }
       });
  • In the onInitDone callback function, use the topic prefix to identify broadcast topics. The prefix of a broadcast topic is /sys/${productKey}/${deviceName}/broadcast/request/.
    public void onInitDone(InitResult initResult) {
                    // Set the listener to listen for downstream messages.
                    IConnectNotifyListener notifyListener = new IConnectNotifyListener() {
                        // Define the callback that is invoked to process downstream messages.
                        @Override
                        public void onNotify(String connectId, String topic, AMessage aMessage) {
                            // Filter broadcast messages.
                            if(topic.startsWith(broadcastTopic)){
                                System.out.println(
                                        "received broadcast message from topic=" + topic + ",\npayload=" + new String((byte[])aMessage.getData()));
                            }
                        }
                        @Override
                        public boolean shouldHandle(String s, String s1) {
                            return false;
                        }
                        @Override
                        public void onConnectStateChange(String s, ConnectState connectState) {
                        }
                    };
                    LinkKit.getInstance().registerOnNotifyListener(notifyListener);
                }

Configure the server-side SDK

Configure the server-side Java SDK to send broadcast messages.

  • Configure the authentication information.
     String regionId = "<yourRegionID>";
     String accessKey = "<yourAccessKey>";
     String accessSecret = "<yourAccessSecret>";
     final String productKey = "<yourProductKey>";
  • Configure the server to call the PubBroadcast API operation to broadcast a message.
    // Set client parameters.
    DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
    IAcsClient client = new DefaultAcsClient(profile);
    PubBroadcastRequest request = new PubBroadcastRequest();
    // Set the ProductKey for the broadcast message.
    request.setProductKey(productKey);
    // Set the message content. The content must be Base64-encoded to prevent garbled characters.
    request.setMessageContent(Base64.encode("{\"pwd\":\"2892nd6Y\"}"));
    // Set the instance ID.
    request.setIotInstanceId("iot-cn-***");
  • Send the broadcast message from the server.
    try {
        PubBroadcastResponse response = client.getAcsResponse(request);
    System.out.println("broadcast pub success: broadcastId =" + response.getMessageId());
    } catch (Exception e) {
        System.out.println(e);
    }

Verify the results

Run the device SDK code on each device to connect them. Then, run the server-side SDK code to call the PubBroadcast API operation to broadcast a message to the devices.

The message content broadcast from the server-side SDK is "{\"pwd\":\"2892nd6Y\"}".

The local logs on each device show the received broadcast message: {\"pwd\":\"2892nd6Y\"}.

Smart Lock 1:

2020-03-05  03:17:37.091 – null[MqttDefaulCallback.java] – messageArrived(74):MqttDefaulCallback:messageArrived,topi
  [/sys/a1nTNJt9p39/MjxxxDR/broadcast/request/123546464900384256], msg = [{"pwd":"2892nd6Y"}],
2020-03-05  03:17:37.091 – null[PersistentEventDispatcher.java] – broadcastMessage(150):com.aliyun.alink.linksdk.cha
  what=3
  received broadcast message from topic=/sys/a1nTNJt9p39/MjxxxDR/broadcast/request/123546464900384256,
payload={"pwd":"2892nd6Y"}

Smart Lock 2:

2020-03-05 03:17:37.111 - null[MqttDefaulCallback.java] - messageArrived(74):MqttDefaulCallback:messageArrived,topic
  [/sys/a1nTNJt9p39/W96JAyE7UBpxHkiFy2CG/broadcast/request/1235464464900384256] , msg = [{"pwd":"2892nd6Y"}],
2020-03-05 03:17:37.111 - null[PersistentEventDispatcher.java] - broadcastMessage(150):com.aliyun.alink.linksdk.chan
  what=3
  received broadcast message from topic=/sys/a1nTNJt9p39/W9xxx2CG/broadcast/request/1235464464900384256,
  payload={"pwd":"2892nd6Y"}

Smart Lock 3:

2020-03-05 03:17:37.167 - null[MqttDefaulCallback.java] - messageArrived(74):MqttDefaultCallback:messageArrived,top
  [/sys/a1nTNJt9p39/mBGagyPszmfRbKVzyqvZ/broadcast/request/1235464464900384256] , msg = [{"pwd":"2892nd6Y"}],
2020-03-05 03:17:37.167 - null[PersistentEventDispatcher.java] - broadcastMessage(150):com.aliyun.alink.linksdk.ch
  what=3
  received broadcast message from topic=/sys/a1nTNJt9p39/mlxxxxxxxxxxxvZ/broadcast/request/1235464464900384256,
payload={"pwd":"2892nd6Y"}

Appendix: Demos

Download the complete sample code, which includes examples for the server-side and device-side SDKs.