Paho MQTT for Java connection example

更新时间:
复制 MD 格式

Use the Paho MQTT library for Java to connect a device to IoT Platform and communicate through the thing model.

Prerequisites

You have created a product and a device in IoT Platform. For the product, you have defined a LightSwitch property on the Feature Definitions tab.

For more information, see Create a product, Create a single device, and Add a TSL model for a single device.

Prepare the development environment

Development environment:

Download the Paho MQTT library for Java

Add the following dependency to your Maven project based on your MQTT version:

Important

Visit the official website to check for the latest library version and update the version value accordingly.

  • MQTT 3.1 and 3.1.1

    <dependencies>
      <dependency>
          <groupId>org.eclipse.paho</groupId>
          <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
          <version>1.2.1</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 get the source code for calculating MQTT connection parameters.

    The MqttSign.java file defines the MqttSign class:

    • Prototype:

      class MqttSign
    • Features

      Calculates the username, password, and clientid parameters for an MQTT connection to IoT Platform.

    • Members:

      Type

      Method description

      public void

      calculate(String productKey, String deviceName, String deviceSecret)

      Calculates the MQTT connection parameters username, password, and clientid based on the device's productKey, deviceName, and deviceSecret.

      public String

      getUsername()

      Gets the MQTT connection parameter username.

      public String

      getPassword()

      Gets the MQTT connection parameter password.

      public String

      getClientid()

      Gets the MQTT connection parameter clientid.

  2. Open IntelliJ IDEA and create a project.

  3. Import the MqttSign.java file into your project.

  4. In your project, add a program file to connect the device to IoT Platform.

    Write a program that calls the MqttSign class in MqttSign.java to calculate MQTT connection parameters and connect to IoT Platform.

    Development instructions and sample code:

    • Call MqttSign 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());
    • Use a Paho MQTT client to connect to IoT Platform.

      // The endpoint for connecting to IoT Platform.
      String port = "443";
      String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;
      // The Paho MQTT client.
      MqttClient sampleClient = new MqttClient(broker, sign.getClientid(), persistence);
      // The Paho 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");
      Important

      Modify the endpoint in the code line String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;. The broker value must be in the format "ssl://" + "${MQTT endpoint for your instance}" + ":" + port.

      For more information about the endpoint formats for public and Enterprise instances, see View instance endpoints.

    • Publish a message.

      Report the LightSwitch property defined in the thing model:

      // Publish a message 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);

      For MQTT 5.0, add custom properties when publishing a message:

      // MQTT 5.0 feature: User-defined properties
      MqttProperties properties = new MqttProperties();
      List<UserProperty> userPropertys = new ArrayList<>();
      userPropertys.add(new UserProperty("key1","value1"));
      properties.setUserProperties(userPropertys);
      // MQTT 5.0 feature: request-response mode
      properties.setCorrelationData("requestId12345".getBytes());
      properties.setResponseTopic("/" + productKey + "/" + deviceName + "/user/get");
      message.setProperties(properties);
      // The Paho SDK for MQTT 5.0 uses topic aliases by default.
      sampleClient.publish(topic, message);

      The thing model data format is defined in Device properties, events, and services.

      Custom topic communication is explained in What is a topic?.

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

      Subscribe to a topic to receive property post responses from IoT Platform:

      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 topic using Paho MQTT.
      String topicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";
      sampleClient.subscribe(topicReply, new MqttPostPropertyMessageListener());

    Learn about device-cloud communication patterns in Overview of communications among devices, IoT platform, and servers.

  5. Click the Build Project button build to compile the project.

Run the sample project

Connect a device to IoT Platform using the pre-built sample project.

  1. Download a code package (v3.1.1Demo or v5.0Demo) and decompress it.

  2. Open IntelliJ IDEA and import the aiot-java-demo sample project from the decompressed package.

  3. In the pom.xml file, update the Maven dependency versions as specified in the Download the Paho MQTT library for Java section.

    Important

    If a dependency version is unavailable, check its official repository, such as Maven Central, for a valid version.

  4. In the src/main/java/com.aliyun.iot directory, open the App or Mqtt5App file and replace the sample device credentials with your own.

    Note

    Use the App file for communication over MQTT 3.1 or 3.1.1. Use the Mqtt5App file for communication over MQTT 5.0.

    • In the following code, replace the values of productKey, deviceName, and deviceSecret with your device credentials.

      String productKey = "${ProductKey}";
      String deviceName = "${DeviceName}";
      String deviceSecret = "${DeviceSecret}";
    • Modify the endpoint in the code line String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;, as described in Step 4 of the Connect to IoT Platform section.

  5. Run the App or Mqtt5App program.

    On success, the following logs appear:

    username: example1&a1xxx
    password: 5c9d47198d9d09050043e1f3xxx
    clientid: a1Xxxx.example1|timestamp=1576140939022,_v=paho-java-1.0.0,securemode=2,signmethod=hmacsha256|
    broker: ssl://a1X2bxxx.iot-as-mqtt.cn-shanghai.aliyuncs.com:443 Connected
    subscribe: /sys/a1X2bxxx/example1/thing/event/property/post_reply
    publish: {"id":"1","version":"1.0","params":{"LightSwitch":1}}
    reply topic  : /sys/a1Xxxx/example1/thing/event/property/post_reply
    reply payload: {"code":200,"data":{},"id":"1","message":"success","method":"thing.event.property.post","version":"1.0"}
    Disconnected
    Process finished with exit code 0

    Log in to the IoT Platform console to view device status and logs in your instance.

    • In the left-side navigation pane, choose Device Management > Devices. You can see that the device status is Online.

    • In the left-side navigation pane, choose Maintenance > Device Log. You can view the Cloud-side Log and Device-side Log. Cloud-side Log. Device-side Log.

      If you use the Mqtt5App file, you can view the reported custom properties in the log details.

      In the Property field of the log details, you can find the reported custom property values, such as [{"Value":"value1","Key":"key1"}].

Error codes

If the device fails to connect to IoT Platform over MQTT, use the error codes to troubleshoot the issue. For more information about server-side error codes, see Troubleshooting.