IoT Platform supports broadcast communication. You can broadcast a message to all devices in a product. 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 a message that is broadcasted by a business server. This topic describes how to configure the broadcast communication feature to broadcast a message to all online devices.

Background information

  • Broadcast a message to all online devices in a product

    A business server calls the PubBroadcast operation and configures 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 communication
  • 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 configures 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.

    Important
    • 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 a 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 5 groups. Each group contains 1,000 devices. In this case, you must call the PubBroadcast operation five times. Each time you call the operation, 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

  • Messages can be broadcasted only to online devices in a product.
  • When you broadcast a message to specified online devices, you must specify the broadcast topic to which the devices subscribe. In this case, you can call the PubBroadcast operation 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, you can call the PubBroadcast operation once per minute.
  • The size of a message body can be up to 64 KB.
Important The messages that you want to broadcast to devices are not throttled based on the messaging transactions per second (TPS) specification of the instance to which the devices belong. For example, the messaging TPS specification of an instance is 100 per second and the number of online devices of the instance is 500. When you call the PubBroadcast operation to broadcast a message, the message is sent to the 500 online devices.

Prepare a development environment

In this example, the devices and IoT Platform use SDKs for Java. Therefore, you must prepare a Java development environment. You can download Java from the Java official website and deploy a Java development environment.

Add dependencies to a Maven project

Create a project in Maven. Add the following dependencies to the pom.xml file of the Maven project:

Note The following version number of IoT Platform SDK for Java is a sample value. You can use OpenAPI Explorer to view the information about the SDK dependency.
<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 a device

  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 name to go to the Instance Details page.
    Important Enterprise Edition instances are available in the China (Shanghai) and Japan (Tokyo) regions. If the Enterprise Edition instances are unavailable in the region that you select, skip this step.
    Overview
  3. In left-side navigation pane, choose Devices > Products.
  4. Click Create Product to create a smart door lock product. For more information, see Create a product.
  5. In the left-side navigation pane, choose Devices > Devices. You can create three smart door lock devices in the product that is created. For more information, see Create multiple devices at a time.

Configure the device SDK

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

      The information about the device certificate is specified by the following parameters: productKey, deviceName, and deviceSecret. To view the information, perform the following steps: Log on to the IoT Platform console. On the Overview page, click the card of the instance to which the device belongs. In the left-side navigation page, 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 where the device resides. For more information about the format of the value of the region parameter, see Regions.

    • Configure the parameters to initialize a connection. The parameters include the Message Queuing Telemetry Transport (MQTT) connection parameters, device information, and initial device status.
      LinkKitInitParams params = new LinkKitInitParams();
      // Configure 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";
      // 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;

      channelHost specifies the endpoint for MQTT connections to the instance. For information about how to obtain the endpoints of public instances and Enterprise Edition instances, see View the endpoint of an instance.

    • Initialize the connection.
      // Initialize the connection and configure the callback function that is used after the connection is initialized. 
      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 a 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 a callback function that is used after the downstream messages are received. 
                        @Override
                        public void onNotify(String connectId, String topic, AMessage aMessage) {
    
                            // Filter the received messages to obtain 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.
    // Configure the parameters of the client. 
    DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
    IAcsClient client = new DefaultAcsClient(profile);
    PubBroadcastRequest request = new PubBroadcastRequest();
    // Configure the productKey parameter of the product. 
    request.setProductKey(productKey);
    // Configure the MessageContent parameter. The message content must be encoded in Base64. Otherwise, the message content is displayed as garbled characters. 
    request.setMessageContent(Base64.encode("{\"pwd\":\"2892nd6Y\"}"));
    // Specify the ID of the instance. 
    request.setIotInstanceId("iot-cn-***");
  • 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 code of an IoT Platform SDK and a device 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.