Java Link SDK

Updated at:

This topic demonstrates how to use the Java Link SDK to connect a simulated night light switch to IoT Platform over MQTT and report data by using a custom topic.

Prerequisites

The IoT Platform service has been activated.

Note

You are not charged for activating IoT Platform. You can try the service for free. For more information, see Alibaba Cloud Free Tier for IoT Platform. For information about billing, see Billing overview.

Create a product and a device

  1. Log on to the IoT Platform console and click the target instance card.

  2. In the left-side navigation pane, choose Devices > Products, then click Create Product.

  3. On the Create Product page, set the Product Name to Night Light Switch, select Custom Category for Category, leave the other parameters at their default values, then click OK.

  4. After the product is created, click Add in the Add Device section.

  5. On the Devices page, click Add Device.

  6. In the Add Device dialog box, enter a device name, such as LightSwitch. Then, click OK.

    Enter Quick start in the Remark Name field.

  7. In the The devices have been added. dialog box, click Copy Device Certificate. Save the device certificate information for later use. For more information about device certificates, see Device certificates.

Set up the development environment

This example uses Java 15 and IntelliJ IDEA Community Edition 2020.1. For more information about the environment, see Environment description.

  1. Install Java.

    For more information, see the Java official website.

  2. Install IntelliJ IDEA.

    For more information, see IntelliJ IDEA.

Configure the device SDK

  1. Download the demo file to your development environment and decompress the package.

    Note

    By downloading this demo, you agree to the Software License Agreement.

  2. Open IntelliJ IDEA, choose File > Open..., find the project file, then click OK.

  3. Configure the parameters in the following project files.

    • In the ./device_id.json file, configure the device connection information to connect the device to IoT Platform.

      Parameter

      Example

      Description

      productKey

      a18wP******

      Device credentials. This is the certificate information you saved after adding the device.

      You can also view the device credential information on the Device Details page in the IoT Platform console. For more information, see Obtain device credentials.

      deviceName

      LightSwitch

      deviceSecret

      uwMTmVAMnGGHaAkqmeDY6cHxxB******

      region

      cn-shanghai

      The ID of the region where the device connects to IoT Platform. For more information, see Regions and zones.

      instanceId

      iot-w2******

      The instance ID. You can view the instance ID on the Instance Overview tab of the IoT Platform console.

      If no ID is available, you can omit this parameter.

    • Configure the topic that the device uses to send messages, such as /a18wP******/LightSwitch/user/update, and set the message content. The following code provides an example:

      
          public void publish() {
              MqttPublishRequest request = new MqttPublishRequest();
              request.topic = "/" + productKey + "/" + deviceName + "/user/update";
              request.qos = 0;
              request.payloadObj = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}";
              LinkKit.getInstance().publish(request, new IConnectSendListener() {
                  @Override
                  public void onResponse(ARequest aRequest, AResponse aResponse) {
                      // Publish result
                      ALog.d(TAG, "onResponse " + (aResponse == null ? "" : aResponse.data));
                  }
                  @Override
                  public void onFailure(ARequest aRequest, AError aError) {
                      // Publish failed
                      ALog.d(TAG, "onFailure " + (aError == null ? "" : (aError.getCode() + aError.getMsg())));
                  }
              });
          }

      File

      Parameter

      Example

      Description

      ./src/main/java/com/aliyun/alink/devicesdk/demo/MqttSample.java

      topic

      "/" + productKey + "/" + deviceName + "/user/update"

      The topic that the device uses to send messages to IoT Platform. It must have Publish permission.

      In the IoT Platform console, on the Product Details page, go to the Topic List tab. On the Custom Topics tab, you can view the product's custom topics. For more information, see What is a topic?.

      The user/update part of the example value is the topic suffix. You can modify this part to send messages to a different topic.

      In this example, the destination topic is /a18wP******/LightSwitch/user/update.

      • a18wP****** is the device ProductKey.

      • LightSwitch is the device DeviceName.

      payloadObj

      {\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}

      The message payload to report to IoT Platform.

      This example uses a custom topic. You can define a custom data format for messages.

    • Configure the device to subscribe to a topic, such as /a18wP******/LightSwitch/user/get, to receive messages from IoT Platform. The following code provides an example:

          public void subscribe() {
              MqttSubscribeRequest request = new MqttSubscribeRequest();
              request.topic = "/" + productKey + "/" + deviceName + "/user/get";
              request.isSubscribe = true;
              LinkKit.getInstance().subscribe(request, new IConnectSubscribeListener() {
                  @Override
                  public void onSuccess() {
                      // Subscription succeeded
                      ALog.d(TAG, "onSuccess ");
                  }
                  @Override
                  public void onFailure(AError aError) {
                      // Subscription failed
                      ALog.d(TAG, "onFailure " + getError(aError));
                  }
              });
          }
                                      

      File

      Parameter

      Example

      Description

      ./src/main/java/com/aliyun/alink/devicesdk/demo/MqttSample.java

      topic

      "/" + productKey + "/" + deviceName + "/user/get"

      The topic that the device uses to receive messages from IoT Platform. It must have Subscribe permission.

      In the IoT Platform console, on the Product Details page, go to the Topic List tab. On the Custom Topics tab, you can view the product's custom topics. For more information, see What is a topic?.

      The user/get part of the example value is the topic suffix. You can modify this part to subscribe to a different topic.

      In this example, the subscribed topic is /a18wP******/LightSwitch/user/get.

      • a18wP****** is the device ProductKey.

      • LightSwitch is the device DeviceName.

Verify the results

  • After you configure the project files, click Run to run the ./demo/HelloWorld.java file.

    • The following log indicates that the LightSwitch device is connected to IoT Platform.

      2021-05-07 06:32:05.360 - 20/? D/ConnectManager:CommonNofity, onConnectStateChange(),state = CONNECTED
    • The following log indicates that the LightSwitch device subscribed to the /a18wP******/LightSwitch/user/get topic.

      2021-05-07 06:32:05.493 - null[MqttSendExecutor.java] - asyncSend(162):MqttSendExecutor:subscribe: topic: [ /a18wP******/LightSwitch/user/get ]

      After the device successfully subscribes to the topic, return to the IoT Platform console. On the Device Details page, click the Topic List tab. Find the subscribed topic and click Publish Message in the Actions column. In the Publish Message dialog box, enter a message, such as This is a test message from Alibaba Iot Platform., to simulate sending a message from IoT Platform to the device.

    • The following log indicates that the LightSwitch device reported a message to IoT Platform by using the /a18wP******/LightSwitch/user/update topic.

      2021-05-07 06:32:05.488 - null[MqttSendExecutor.java] - asyncSend(129):MqttSendExecutor:publish: topic: [ /a18wP******/LightSwitch/user/update ]
      2021-05-07 06:32:05.489 - null[MqttSendExecutor.java] - asyncSend(130):MqttSendExecutor:publish: payload: [ {\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}} ]
  • You can view the device status and logs in the IoT Platform console.

    • In the left-side navigation pane, choose Devices > Devices. Find the device and check its status. If the status is Online, the device is connected to IoT Platform.

    • In the left-side navigation pane, choose Maintenance > Device Log. Select the Night Light Switch product to view the logs for device connection, topic subscription, and data reporting.

      Note

      You can ignore logs related to over-the-air (OTA) updates, Thing Specification Language (TSL) models, and sub-devices. This information relates to advanced SDK features and does not affect this quick start.

If an error occurs during testing, see Error codes received on the device and follow the instructions to resolve the issue.

Next steps

After the device is connected to IoT Platform, you can manage the device and perform monitoring and O&M. For more information about the features of IoT Platform, see IoT Platform features.

To configure advanced features using the Java Link SDK, see Java Link SDK overview.