Server-side subscription (MNS)

更新时间:
复制 MD 格式

This topic describes how to configure a server-side subscription to push device status change notifications for a product to a Simple Message Queue (formerly MNS) (SMQ) queue. Your server can then receive these notifications by listening to the MNS queue.

Prerequisites

Configure a server-side subscription

In the IoT Platform console, create a server-side subscription for MNS and select the message types you want to subscribe to.

  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 navigation pane on the left, choose Devices > Products. Then, click Create Product to create a gas detector product.

  4. Choose Devices > Add Device to create a device under the gas detector product.

    The device certificate is required when you configure the device-side SDK.

  5. In the navigation pane on the left, choose Rules Engine > Server-side Subscription. Then, click Create Subscription to create a server-side subscription for MNS. For more information, see Use server-side subscriptions for MNS.

    Note

    When you set up message forwarding to MNS for the first time, you must click Authorize in the prompt. You are then redirected to the RAM console to grant IoT Platform access to MNS.

    In this example, select Device Status Change Notification as the message type. This ensures that all device status change notifications for the product are pushed to the MNS queue.

    After the subscription is created, IoT Platform automatically creates a queue in MNS to receive messages. The queue name is in the format aliyun-iot-${yourProductKey}. You must use this queue name when you configure the MNS SDK to listen for messages.

    In the subscription list, click the icon next to MNS to view the MNS queue name.

Configure the server-side MNS SDK

This example uses the MNS SDK for Java demo.

  1. Go to the MNS SDK for Java release notes, download the sample package, and decompress it.

    This example uses the aliyun-sdk-mns-samples-1.1.9.1.zip sample package.

  2. In IntelliJ IDEA, import the aliyun-sdk-mns-samples-1.1.9.1 folder as a project.

  3. In your local directory at C:\Users\${YourComputerUserName}, create a properties file named .aliyun-mns.properties. In this file, add your MNS authentication credentials in the following format:

    Note

    The home directory in Linux is /home/YOURNAME/. The home directory in Windows is C:\Users\YOURNAME.

    mns.accountendpoint=http://${your_accountId}.mns.${your_regionId}.aliyuncs.com
    mns.accesskeyid=${your_accesskeyid}
    mns.accesskeysecret=${your_accesskeysecret}

    Parameter

    Description

    accountendpoint

    The endpoint for your MNS service. You can find this in the Message Service (MNS) console. Select the region where your queue is located and click Details for the queue.

    accesskeyid

    The AccessKey ID and AccessKey secret of your Alibaba Cloud account.

    Log on to the IoT Platform console, move the pointer over the profile picture, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.

    accesskeysecret

  4. In the ComsumerDemo.java file, located in the src\main\java\com.aliyun.mns.sample.Queue directory, specify the name of the Simple Message Queue (formerly MNS) queue automatically created by IoT Platform.

        public static void main(String[] args) {
            CloudAccount account = new CloudAccount(
                    ServiceSettings.getMNSAccessKeyId(),
                    ServiceSettings.getMNSAccessKeySecret(),
                    ServiceSettings.getMNSAccountEndpoint());
            MNSClient client = account.getMNSClient(); // Initialize the client.
            // Consume messages.
            try{
                CloudQueue queue = client.getQueueRef("aliyun-iot-a1eN7La****");// Replace this with the queue name automatically created by IoT Platform.
                for (int i = 0; i < 10; i++)
                {
                    Message popMsg = queue.popMessage(); // Pop a message from the queue.
                    if (popMsg != null){
                        System.out.println("message handle: " + popMsg.getReceiptHandle());
                        System.out.println("message body: " + popMsg.getMessageBodyAsString()); // Get the raw message body.
                        System.out.println("message id: " + popMsg.getMessageId());
                        System.out.println("message dequeue count:" + popMsg.getDequeueCount());
                        // Add your message processing logic here.
                        // Delete the message from the queue.
                        queue.deleteMessage(popMsg.getReceiptHandle());
                        System.out.println("delete message successfully.\n");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
  5. Run the ComsumerDemo.java file.

Configure the device-side SDK

  1. Go to Link SDK and select SDK for Java.

  2. In the Environment requirements and configuration topic for the Link SDK for Java, download the Java SDK demo and decompress the package.

  3. In IntelliJ IDEA, import the JavaLinkKitDemo project.

  4. In the device_id file, enter your device certificate information.

    {
      "productKey": "xxx",
      "deviceName": "Esensor",
      "productSecret": "",
      "deviceSecret": "1xxx?2"
    }
  5. In the MqttSample.java file, located in the src\main\java\com.aliyun.alink.devicesdk.demo directory, set the publish topic to your device topic.

    public class MqttSample extends BaseSample {
        final static String TAG = "MqttSample";
        public MqttSample(String pk, String dn) { super(pk, dn); }
        /**
         * An example of the publishing API.
         */
        public void publish() {
            MqttPublishRequest request = new MqttPublishRequest();
            // Specify the topic based on your use case.
            request.topic = "/sys/" + productKey + "/" + deviceName + "/thing/deviceinfo/update";
        }
    }
  6. In the HelloWorld.java file, located in the src\main\java\com.aliyun.alink.devicesdk.demo directory, enter the device connection information.

    To obtain device connection information, see View and configure instance endpoints. The channelHost format is {productKey}.iot-as-mqtt.{region}.aliyuncs.com:1883. Example code:

    public void init(final DeviceInfoData deviceInfoData) {
        this.pk = deviceInfoData.productKey;
        this.dn = deviceInfoData.deviceName;
        LinkKitInitParams params = new LinkKitInitParams();
        /**
         * Set MQTT initialization parameters.
         */
        IoTMqttClientConfig config = new IoTMqttClientConfig();
        config.productKey = deviceInfoData.productKey;
        config.deviceName = deviceInfoData.deviceName;
        config.deviceSecret = deviceInfoData.deviceSecret;
        config.channelHost = pk + ".iot-as-mqtt." + deviceInfoData.region + ".aliyuncs.com:1883";
        /**
         * Specifies whether to receive offline messages.
         * This corresponds to the cleanSession field in MQTT.
         */
        // ...
    }
  7. Run the HelloWorld.java file to connect the device.

Verify the results

After the device-side SDK runs, the device online notification is sent to the Simple Message Queue (formerly MNS) queue through the server-side subscription. The Simple Message Queue (formerly MNS) SDK then consumes the message from the queue and deletes it.

The following example shows the output when the Simple Message Queue (formerly MNS) SDK successfully receives and deletes a message.

message handle: 519xxx...AgMA==
message body:
  {"payload":"eyJsYXN0xxx...IiwiY2xpZW5xxx...","topic":"/as/mqtt/status/xxx/device1","messageid":15xxx,"timestamp":1661158432}
message id: 51xxx...C49
message dequeue count:1
delete message successfully.