IoT Platform supports broadcast communication. You can enable IoT Platform to broadcast a message to all online devices under a product. The devices do not need to subscribe to a broadcast topic to receive the message sent by the server.

Background information

A manufacturer has multiple smart door locks that are connected to IoT Platform. Currently, the manufacturer needs the 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 of the product and MessageContent. 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 Alibaba Cloud. After being sent, the 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 under 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 visit the Java official website to download and install the Java IDE.

Add the following Maven dependencies to import the device SDK (Link SDK for Java) and IoT Platform 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 under the product that has been created.

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

Configure the device SDK

Configure the Link Kit SDK for Java 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>";

      productKey, deviceName, and deviceSecret: the device authentication information. You can view the parameter values on the Device Details page of the IoT Platform console.

      region: the ID of the region in which the device resides. For a list of region IDs, see Regions and zones.

    • Set connection initialization parameters, including MQTT connection information, device information, and initial device status.
      LinkKitInitParams params = new LinkKitInitParams();
      // Configure MQTT connection information. 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";
      // Configure device information.
      DeviceInfo deviceInfo = new DeviceInfo();
      deviceInfo.productKey = productKey;
      deviceInfo.deviceName = deviceName;
      deviceInfo.deviceSecret = deviceSecret;
      // Register the initial device status.
      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 a callback function that is used after the initialization is successful.
      LinkKit.getInstance().init(params, new ILinkKitConnectListener() {
           @Override
           public void onError(AError aError) {
               System.out.println("Init error:" + aError);
           }
           // Configure the callback function that is used after the initialization is successful.
           @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 as follows: /sys/${productKey}/${deviceName}/broadcast/request/.
    public void onInitDone(InitResult initResult) {
    
                    // Configure a callback function that is used after a subscribed message is received.
                    IConnectNotifyListener notifyListener = new IConnectNotifyListener() {
                        // Define the callback function that is used after a subscribed message is received.
                        @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 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.
    // Configure 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 for broadcasting the message.
    request.setProductKey(productKey);
    // Set the message content. The message content must be encoded in Base64. Otherwise, the message content will be 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 is displayed 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.