This topic describes how to use the Paho MQTT Java client to access Alibaba Cloud IoT Platform for message exchanges.

Prerequisites

Products and devices are created in IoT Platform, and a LightSwitch property is defined on the Define Feature tab page.

For more information, see Create a product, Create a device, and Define features.

Prepare the development environment

The following describes the development environment for this example.

Download the Java Paho MQTT library

Add the following dependencies to the Maven project:

<dependencies>
  <dependency>
      <groupId>org.eclipse.paho</groupId>
      <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
      <version>1.2.0</version>
    </dependency>
</dependencies>

Connect to IoT Platform

  1. Click MqttSign.java to download the code provided by Alibaba Cloud for calculating the MQTT connection parameters.

    The MqttSign.java file defines the MqttSign class.

    • Prototype
      class MqttSign
    • Functionality

      Calculates the username, password, and clientId parameters for MQTT connections to IoT Platform.

    • Methods
      Type Method description
      public void calculate(String productKey, String deviceName, String deviceSecret)

      You can call this method to calculate the username, password, and clientid based on the productKey, deviceName, and deviceSecret of the device.

      public String getUsername()

      You can call this method to obtain the MQTT connection parameter username.

      public String getPassword()

      You can call this method to obtain the MQTT connection parameter password.

      public String getClientid()

      You can call this method to obtain the MQTT connection parameter clientid.

  2. Open IntelliJ IDEA and create a project.
  3. Import the MqttSign.java file into the project.
  4. In the project, add a program file that enables devices to access IoT Platform.

    You must write a program which can call the MqttSign class in the MqttSign.java file to calculate the parameters for MQTT connections and connect to IoT Platform.

    The instructions for development and sample code are as follows.

    • Use the MqttSign class to calculate the MQTT connection parameters.
      String productKey = "****";
      String deviceName = "Lamp";
      String deviceSecret = "ga7XA6KdlEeiPXQPpRbAjOZXwG8y****";
      
      // Calculate the MQTT connection parameters
      MqttSign sign = new MqttSign();
      sign.calculate(productKey, deviceName, deviceSecret);
      
      System.out.println("username: " + sign.getUsername());
      System.out.println("password: " + sign.getPassword());
      System.out.println("clientid: " + sign.getClientid());
    • Call the Paho MQTT client to connect to IoT Platform.
      // The domain name to access IoT Platform.
      String port = "443";
      String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;
      
      // Paho MQTT client
      MqttClient sampleClient = new MqttClient(broker, sign.getClientid(), persistence);
      
      // Connection parameters for Paho MQTT.
      MqttConnectOptions connOpts = new MqttConnectOptions();
      connOpts.setCleanSession(true);
      connOpts.setKeepAliveInterval(180);
      connOpts.setUserName(sign.getUsername());
      connOpts.setPassword(sign.getPassword().toCharArray());
      sampleClient.connect(connOpts);
      System.out.println("Broker: "+ broker +" Connected");
      Note Replace cn-shanghai in the code with the region ID of your IoT Platform device. For more information about region IDs, see Regions and zones.
    • Publish messages.

      The following sample code is used to report the value of LightSwitch property to IoT Platform.

      // Publish messages with Paho MQTT
      String topic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
      String content = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":1}}";
      MqttMessage message = new MqttMessage(content.getBytes());
      message.setQos(0);
      sampleClient.publish(topic, message);

      For more information about the TSL data format, see Device properties, events, and services.

      If you want to use custom topics for communication, see What is a topic?.

    • Subscribe to topics for obtaining messages sent from IoT Platform.

      You can use the following example to subscribe to the topic for the response messages of IoT Platform after the property values are reported.

      class MqttPostPropertyMessageListener implements IMqttMessageListener {
          @Override
          public void messageArrived(String var1, MqttMessage var2) throws Exception {
              System.out.println("reply topic  : " + var1);
              System.out.println("reply payload: " + var2.toString());
          }
      }
      ...
      // The topic to which Paho MQTT subscribes for messages
      String topicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";
      sampleClient.subscribe(topicReply, new MqttPostPropertyMessageListener());

    For more information about the communication methods of devices, servers, and IoT Platform, see Communication methods.

  5. Compile the project.

Demo

Use the demo code to access IoT Platform.

  1. Download the demo package. Then decompress the package.
  2. Open IntelliJ IDEA and import the sample project aiot-java-demo from the demo package.
  3. In the src/main/java/com.aliyun.iot/App file, change the device information to your device information.
    • Replace the productKey, deviceName, and deviceSecret with your device certificate information.
    • Replace cn-shanghai in String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port; with the region ID of your IoT Platform device. For more information about region IDs, see Regions and zones.
  4. Run the App program.

    In the IoT Platform console, you can view the device status and logs.

    • Choose Devices > Devices. You can view that the status of the device is Online.
    • Choose Maintenance > Device Log. You can view the Device Activity Analysis and Upstream Analysis logs.