IoT Platform supports broadcast communication. You can enable IoT Platform to broadcast a message to multiple devices under a product. The devices do not need to subscribe to a broadcast topic to receive the message sent by the server. This topic describes how to configure broadcast communication.

Background information

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

The business server calls the PubBroadcast operation and specifies the ProductKey and MessageContent parameters of the product. 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. The sent message is returned to the business server who called the PubBroadcast operation.

Broadcast messages

Limits

  • Broadcast messages can be pushed only to the online devices in the product.
  • The maximum frequency of calling the PubBroadcast operation is once per minute.
  • The size of a message body can be up to 64 KB.

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 tools at the Java official website and install the Java development environment.

Add the following Maven dependencies to import the device SDK (Link Kit Java SDK) and IoT SDK:

<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 the 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 and create two smart door locks in the product that is created.

    For more information, see Create multiple devices at a time.

Configure the device SDK

Configure the Link SDK to access IoT Platform.

  • 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, choose Devices > Devices, and click View next to the required device. The information appears on the Device Details page.

      The region parameter specifies the region where the device resides. For more information about the format of the region parameter, see the Region ID section of Regions and zones.

    • Set connection initialization parameters. These parameters include the MQTT settings, device information, and initial device status.
      LinkKitInitParams params = new LinkKitInitParams();
      // Set the MQTT connection parameters. Link Kit 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";
      // The device information.
      DeviceInfo deviceInfo = new DeviceInfo();
      deviceInfo.productKey = productKey;
      deviceInfo.deviceName = deviceName;
      deviceInfo.deviceSecret = deviceSecret;
      // Registers 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.
      // Initializes 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);
           }
           // Configures the callback function that is used after the initialization succeeds.
           @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 the topic prefix is /sys/${productKey}/${deviceName}/broadcast/request/.
    public void onInitDone(InitResult initResult) {
    
                    // Configures a callback function that is used after a downstream message is received.
                    IConnectNotifyListener notifyListener = new IConnectNotifyListener() {
                        // Configures the callback functions that are used after a subscribed message is received.
                        @Override
                        public void onNotify(String connectId, String topic, AMessage aMessage) {
    
                            // Filters 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 the IoT Platform SDK

Configure the IoT Platform SDK for Java to broadcast a message.

  • Configure identity verification information.
     String regionId = "<yourRegionID>";
     String accessKey = "<yourAccessKey>";
     String accessSecret = "<yourAccessSecret>";
     final String productKey = "<yourProductKey>";
  • Configure a client to call the PubBroadcast operation of IoT Platform to broadcast a message.
    // Sets the parameters of the client.
    DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
    IAcsClient client = new DefaultAcsClient(profile);
    PubBroadcastRequest request = new PubBroadcastRequest();
    // Sets the productKey parameter of the product to broadcast the message.
    request.setProductKey(productKey);
    // Sets the MessageContent parameter. The message content must be encoded in Base64. Otherwise, the message content will appear as garbled characters.
    request.setMessageContent(Base64.encode("{\"pwd\":\"2892nd6Y\"}"));
  • Send the broadcast message to the client.
    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

Use the 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

Download the following package: PubBroadcastDemo. You can view the complete sample code in the package. This package contains the sample code of the IoT Platform and device SDKs.