This article describes how to use the Paho Message Queuing Telemetry Transport (MQTT) library for Java to connect to IoT Platform and exchange messages with IoT Platform.

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 Add a TSL feature.

Prepare the development environment

In this example, the development environment consists of the following components:

Download the Paho MQTT library for Java

Add dependencies to the Maven project based on the version of the MQTT protocol.

  • MQTT 3.1 and 3.1.1
    <dependencies>
      <dependency>
          <groupId>org.eclipse.paho</groupId>
          <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
          <version>1.2.0</version>
        </dependency>
    </dependencies>
  • MQTT 5.0
    <dependency>
       <groupId>org.eclipse.paho</groupId>
       <artifactId>org.eclipse.paho.mqttv5.client</artifactId>
       <version>1.2.5</version>
    </dependency>

Connect to IoT Platform

  1. Click MqttSign.java to obtain the source code provided by Alibaba Cloud to calculate 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.

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

      You can call this method to calculate the username, password, and clientid parameters 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 can connect a device to IoT Platform.

    You must write a program to use the MqttSign class in the MqttSign.java file to calculate the parameters that are used to establish an MQTT connection to IoT Platform.

    This section provides the development instructions and sample code.

    • Use the MqttSign class to calculate the MQTT connection parameters.
      String productKey = "a1X2bEn****";
      String deviceName = "example1";
      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());
    • Create a Paho MQTT client to connect to IoT Platform.
      // Specify the domain name for connecting to IoT Platform.
      String port = "443";
      String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;
      
      // Create a Paho MQTT client.
      MqttClient sampleClient = new MqttClient(broker, sign.getClientid(), persistence);
      
      // Set the MQTT connection parameters.
      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
    • Publish messages.

      The following sample code is used to report the LightSwitch property of a TSL model.

      // Publish messages by using 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);

      If you use MQTT 5.0, you can add the following sample code to publish messages that contain custom properties.

      // MQTT 5.0 new feature: Report custom properties.
      MqttProperties properties = new MqttProperties();
      List<UserProperty> userPropertys = new ArrayList<>();
      userPropertys.add(new UserProperty("key1","value1"));
      properties.setUserProperties(userPropertys);
      
      // MQTT 5.0 new feature: Set the request and response mode.
      properties.setCorrelationData("requestId12345".getBytes());
      properties.setResponseTopic("/" + productKey + "/" + deviceName + "/user/get");
      
      message.setProperties(properties);
      
      // By default, Paho SDK that supports MQTT 5.0 uses topic aliases.
      sampleClient.publish(topic, message);

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

      For more information about how to use custom topics for communication, see What is a topic?

    • Subscribe to a topic to obtain messages from IoT Platform.

      In this example, you subscribe to the topic to which IoT Platform returns response messages 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());
          }
      }
      ...
      // Subscribe to a message topic by using Paho MQTT.
      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

The demo code demonstrates how to connect a device to IoT Platform.

  1. Download the demo package and decompress it.
  2. Open IntelliJ IDEA and import the sample project aiot-java-demo in the demo package.
  3. In the src/main/java/com.aliyun.iot directory, replace the device information with your device information in the App or Mqtt5App file.
    Note If you use MQTT 3.1 or 3.1.1, replace the device information in the App file. If you use MQTT 5.0, replace the device information in the Mqtt5App file.
    • Replace the values of the productKey, deviceName, and deviceSecret parameters with your device certificate information.
      String productKey = "${ProductKey}";
      String deviceName = "${DeviceName}";
      String deviceSecret = "${DeviceSecret}";
    • Modify the domain name in String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;. For more information, see Step 4 in the "Connect to IoT Platform" section.
  4. Run the App or Mqtt5App program.
    The following figure shows the success logs.result

    Log on to the IoT Platform console.View device status and logs.

    • Choose Devices > Devices. You can find that the status of the device is Online.
    • Choose Maintenance > Device Log to view logs on the Cloud run log and Device local log tabs. For more information, see IoT Platform logs and Local device logs.

      If the Mqtt5App program is run, you can view the reported custom properties in the log details.

Error codes

If a device fails to establish an MQTT connection to IoT Platform, you can troubleshoot the issue based on the error code. For more information about the error codes that may be returned by IoT Platform, see Troubleshooting.