IoT Platform supports broadcast communication. You can broadcast a message to all devices under a product. In this case, the devices do not need to subscribe to a broadcast topic to receive the message. You can also broadcast a message to all devices that subscribe to a specified topic. A device must be online to receive the message that is sent by the server. This article describes how to broadcast a message to all online devices under a product.

Background information

  • Broadcast a message to all online devices under a product

    A business server calls the PubBroadcast operation and specifies the ProductKey and MessageContent parameters. Then, all online devices receive the message from the following broadcast topic: /sys/${productKey}/${deviceName}/broadcast/request/${MessageId}.

    The message ID in the broadcast topic is generated by IoT Platform. After the message is sent, the message ID is returned to the business server that calls the PubBroadcast operation.

    For example, a manufacturer has multiple smart door locks that are connected to IoT Platform. The manufacturer uses a business server to send a command to all online devices to invalidate a password.

    Broadcast a message
  • Broadcast a message to all devices that subscribe to a specified topic

    The devices subscribe to the same broadcast topic. A business server calls the PubBroadcast operation and specifies the ProductKey, MessageContent, and Topic parameters. The format of a broadcast topic is /broadcast/${productKey}/Custom field. Then, all online devices receive the message from the topic.

    Notice
    • When you develop devices, use code to define a broadcast topic. You do not need to create a topic in the IoT Platform console.
    • A maximum of 1,000 devices can subscribe to the same broadcast topic. If the number of devices exceeds the limit, you can divide the devices into groups. For example, you can divide 5,000 devices into five groups. Each group contains 1,000 devices. You must call the PubBroadcast operation five times, and each time set the custom field in the broadcast topic to group1, group2, group3, group4, and group5. Make sure that each group of devices subscribes to the required broadcast topic.

    For more information about how to call the PubBroadcast operation, see PubBroadcast.

Limits

  • Broadcast messages can be pushed only to online devices under a product.
  • When you broadcast a message to specified online devices, specify the broadcast topic to which the devices subscribe. In this case, the maximum frequency of calling the PubBroadcast operation is once per second.
  • When you broadcast a message to all online devices, the devices do not need to subscribe to a broadcast topic. In this case, the maximum frequency of calling the PubBroadcast operation is once per minute.
  • The size of a message body can be up to 64 KB.
Notice Broadcast messages are not throttled by the limit of transactions per second (TPS) in messaging. For example, the limit of TPS in messaging is 100 per second and the number of current online devices is 500. Each time you call the PubBroadcast operation, the message is sent to 500 online devices.

Prepare the development environment

In this example, both devices and IoT Platform use SDKs for Java. You need to prepare the Java development environment first. You can download Java from the Java official website and install the Java development environment.

Add Maven dependencies

Create a project. In the pom.xml file, add the following Maven dependencies:

<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>3.7.1</version>
  </dependency>
  <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>aliyun-java-sdk-iot</artifactId>
      <version>7.6.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. In left-side navigation pane, choose Devices > Products.
  3. Click Create Product to create a smart door lock product. For more information, see Create a product.
  4. In the left-side navigation pane, choose Devices > Devices. Then, you can create three smart door lock devices under the product that is created. For more information, see Create multiple devices at a time.

Configure the device SDK

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

      The productKey, deviceName, and deviceSecret parameters specify the device certificate information. To view the information, go to the IoT Platform console.In the left-side navigation pane, choose Devices > Devices. On the page that appears, find the device and click View in the Actions column. The information is displayed on the Device Details page.

      region: the ID of the region in which the device resides. For more information about region IDs, see Regions and zones.

    • Set the parameters to initialize a connection. These parameters include the MQTT connection parameters, device information, and initial device status.
      LinkKitInitParams params = new LinkKitInitParams();
      // Set the MQTT connection parameters. Link SDK uses MQTT as the underlying protocol. 
      IoTMqttClientConfig config = new IoTMqttClientConfig();
      config.productKey = productKey;
      config.deviceName = deviceName;
      config.deviceSecret = deviceSecret;
      config.channelHost = productKey + ".iot-as-mqtt." + region + ".aliyuncs.com:1883";
      // Set the device information. 
      DeviceInfo deviceInfo = new DeviceInfo();
      deviceInfo.productKey = productKey;
      deviceInfo.deviceName = deviceName;
      deviceInfo.deviceSecret = deviceSecret;
      // Set the initial status of the device. 
      Map<String, ValueWrapper> propertyValues = new HashMap<String, ValueWrapper>();
      params.mqttClientConfig = config;
      params.deviceInfo = deviceInfo;
      params.propertyValues = propertyValues;
    • Initialize the connection.
      // Initialize the connection and configure the callback function that is used after the initialization succeeds. 
      LinkKit.getInstance().init(params, new ILinkKitConnectListener() {
           @Override
           public void onError(AError aError) {
               System.out.println("Init error:" + aError);
           }
           // Implement the callback function. 
           @Override
           public void onInitDone(InitResult initResult) {
               System.out.println("Init done:" + initResult);
           }
       });
  • The onInitDone() callback function uses the prefix to identify broadcast topics. The syntax of a topic prefix is /sys/${productKey}/${deviceName}/broadcast/request/.
    public void onInitDone(InitResult initResult) {
    
                    // Configure a callback function that is used when downstream messages are sent. 
                    IConnectNotifyListener notifyListener = new IConnectNotifyListener() {
                        // Configure the callback function that is used after the downstream messages are received. 
                        @Override
                        public void onNotify(String connectId, String topic, AMessage aMessage) {
    
                            // Filter the received 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 IoT Platform SDK

Configure IoT Platform SDK for Java to broadcast a message.

  • Specify identity information for verification.
     String regionId = "<yourRegionID>";
     String accessKey = "<yourAccessKey>";
     String accessSecret = "<yourAccessSecret>";
     final String productKey = "<yourProductKey>";
  • Call the PubBroadcast operation of IoT Platform to broadcast a message.
    // Set the parameters of the client. 
    DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
    IAcsClient client = new DefaultAcsClient(profile);
    PubBroadcastRequest request = new PubBroadcastRequest();
    // Set the productKey parameter of the product. 
    request.setProductKey(productKey);
    // Set the MessageContent parameter. The message content must be encoded in Base64. Otherwise, the message content appears as garbled characters. 
    request.setMessageContent(Base64.encode("{\"pwd\":\"2892nd6Y\"}"));
  • Broadcast the message.
    try {
        PubBroadcastResponse response = client.getAcsResponse(request);
    System.out.println("broadcast pub success: broadcastId =" + response.getMessageId());
    } catch (Exception e) {
        System.out.println(e);
    }

Verify the operation

Configure Link SDK on devices to connect the devices to IoT Platform. Then, configure IoT Platform SDK to call the PubBroadcast operation to broadcast a message to the devices.

Use IoT Platform SDK to send the following message to devices: "{\"pwd\":\"2892nd6Y\"}".

The following message appears in the on-premises logs of the devices: {\"pwd\":\"2892nd6Y\"}.

Door Lock 1:

Door Lock 1

Door Lock 2:

Door Lock 2

Door Lock 3:

Door Lock 3

Appendix: Sample code

You can view the following sample codes of IoT Platform SDK and Link SDK:

  • PubBroadcastDemo. The sample code is used to broadcast a message to all online devices.
  • BroadcastDemo. The sample code is used to broadcast a message to all devices that subscribe to a specified topic.