×
Community Blog Usage Tips for the IoT Platform: Retrieving Device Status by Calling API Operations

Usage Tips for the IoT Platform: Retrieving Device Status by Calling API Operations

Alibaba Cloud IoT Platform provides multiple cloud API operations for retrieving the device status. This article describes how to call these API operations.

Principle

In several IoT service scenarios, the real-time status of devices is imperative for state-specific (online or offline) processing. Alibaba Cloud IoT Platform provides multiple cloud API operations for retrieving the device status. This article explains how to call these API operations.

The device status is retrievable through the following API operations. Select API operations based on your service requirements.

1

Implementation

This article uses the Java SDK as an example, which requires the Java development environment as a preliminary. In the Maven project, add the following pom dependency to install Alibaba Cloud IoT SDK.

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>3.5.1</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-iot</artifactId>
  <version>6.11.0</version>
</dependency>
<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.13</version>
</dependency>

Now, set Config. Parameters to the AccessKey ID and AccessKey secret of the Alibaba Cloud account as well as the device information, respectively.

  // The region ID of your IoT Platform service. For more information, see https://help.aliyun.com/document_detail/40654.html.
  private static String regionId = "cn-shanghai";
  // The AccessKey ID of your Alibaba Cloud account.
  private static String accessKeyID = "Config.accessKey";
  // The AccessKey Secret of your Alibaba Cloud account.
  private static String accessKeySecret = "Config.accessKeySecret";
  // The unique identifier of the product to which the queried device belongs.
  private static String productKey = "Config.productKey";
  // The name of the queried device.
  private static String deviceName = "Config.deviceName";

Consider the sample code below.

/*   
 * Copyright © 2019 Alibaba. All rights reserved.
 */
package com.aliyun.iot.demo.checkstatus;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.BatchGetDeviceStateRequest;
import com.aliyuncs.iot.model.v20180120.BatchGetDeviceStateResponse;
import com.aliyuncs.iot.model.v20180120.BatchGetDeviceStateResponse.DeviceStatus;
import com.aliyuncs.iot.model.v20180120.BatchQueryDeviceDetailRequest;
import com.aliyuncs.iot.model.v20180120.BatchQueryDeviceDetailResponse;
import com.aliyuncs.iot.model.v20180120.BatchQueryDeviceDetailResponse.DataItem;
import com.aliyuncs.iot.model.v20180120.GetDeviceStatusRequest;
import com.aliyuncs.iot.model.v20180120.GetDeviceStatusResponse;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailRequest;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailResponse;
import com.aliyuncs.iot.model.v20180120.RRpcRequest;
import com.aliyuncs.iot.model.v20180120.RRpcResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

public class GetDeviceStatusByApi {

  // ===================The list of required parameters begins here===========================
  // Set Config. * parameters based on your information.
  // The region ID of your IoT Platform service. For more information, see https://help.aliyun.com/document_detail/40654.html.
  private static String regionId = "cn-shanghai";
  // The AccessKey ID of your Alibaba Cloud account.
  private static String accessKeyID = "Config.accessKey";
  // The AccessKey Secret of your Alibaba Cloud account.
  private static String accessKeySecret = "Config.accessKeySecret";
  // The unique identifier of the product to which the queried device belongs.
  private static String productKey = "Config.productKey";
  // The name of the queried device.
  private static String deviceName = "Config.deviceName";
  // ===================The list of required parameters ends here===========================

  private static DefaultAcsClient client = null;

  private static DefaultAcsClient getClient(String accessKeyID, String accessKeySecret) {

    if (client ! = null) {
      return client;
    }

    try {
      IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
      DefaultProfile.addEndpoint(regionId, regionId, "Iot", "iot." + regionId + ".aliyuncs.com");
      client = new DefaultAcsClient(profile);
    } catch (Exception e) {
      System.out.println("create Open API Client failed !! exception:" + e.getMessage());
    }

    return client;
  }

  /**
   * Retrieves the device status.
   * Methods 1, 2, 3, and 4 are status-based queries. The retrieved status values may be updated with a delay due to network and heartbeat packet latency.
   * Method 5 is based on synchronous communication and returns more accurate results.
   * 
   * @param args
   * @throws ServerException
   * @throws ClientException
   */
  public static void main(String[] args) throws ServerException, ClientException {

    // Retrieves the client that sends a request to the server.
    DefaultAcsClient client = getClient(accessKeyID, accessKeySecret);

    GetDeviceStatusByApi api = new GetDeviceStatusByApi();

    // Method 1
    api.ByGetDeviceStatus(client);

    // Method 2
    api.ByBatchGetDeviceState(client);

    // Method 3
    api.ByQueryDeviceDetail(client);

    // Method 4
    api.ByBatchQueryDeviceDetail(client);

    // Method 5
    api.ByRRpc(client);
  }

  /**
   * Queries the running status of a single device.
   * GetDeviceStatus https://help.aliyun.com/document_detail/69617.html
   * 
   * @param client // The client that sends a request to the server.
   * @throws ServerException
   * @throws ClientException
   */
  public void ByGetDeviceStatus(DefaultAcsClient client) throws ServerException, ClientException {

    // Fills in the request.
    GetDeviceStatusRequest request = new GetDeviceStatusRequest();
    request.setProductKey(productKey); // The unique identifier of the product to which the target device belongs.
    request.setDeviceName(deviceName); // The name of the target device.

    // Obtains a response.
    GetDeviceStatusResponse response = (GetDeviceStatusResponse) client.getAcsResponse(request);
    if (response ! = null && response.getSuccess()) {
      GetDeviceStatusResponse.Data data = response.getData();
      // ONLINE: The device is online.
      // OFFLINE: The device is offline.
      // UNACTIVE: The device is inactive.
      // DISABLE: The device is disabled.
      if ("ONLINE".equals(data.getStatus())) {
        System.out.println("GetDeviceStatus detection:" + deviceName + "The device is online.");
      } else { // Other states are considered that the device is offline. You can also determine the device status based on services.
        System.out.println("GetDeviceStatus detection:" + deviceName + "The device is offline.");
      }
    } else {
      System.out.println("GetDeviceStatus detection:" + "The API call fails. The device" + deviceName + "may not exist.");
    }
  }

  /**
   * Queries the running status of devices in batches.
   * BatchGetDeviceState https://help.aliyun.com/document_detail/69906.html
   * 
   * @param client // The client that sends a request to the server.
   * @throws ServerException
   * @throws ClientException
   */
  public void ByBatchGetDeviceState(DefaultAcsClient client) throws ServerException, ClientException {

    // Fills in the request.
    BatchGetDeviceStateRequest request = new BatchGetDeviceStateRequest();
    request.setProductKey(productKey); // The unique identifier of the product to which the target device belongs.
    List<String> deviceNames = new ArrayList<String>(); // A list of target device names.
    deviceNames.add(deviceName);
    request.setDeviceNames(deviceNames);

    // Obtains a response.
    BatchGetDeviceStateResponse response = (BatchGetDeviceStateResponse) client.getAcsResponse(request);
    if (response ! = null && response.getSuccess()) {
      List<DeviceStatus> dsList = response.getDeviceStatusList();
      for (DeviceStatus ds : dsList) {
        // ONLINE: The device is online.
        // OFFLINE: The device is offline.
        // UNACTIVE: The device is inactive.
        // DISABLE: The device is disabled.
        if ("ONLINE".equals(ds.getStatus())) {
          System.out.println("BatchGetDeviceState detection:" + ds.getDeviceName() + "The device is online.");
        } else { // Other states are considered that the device is offline. You can also determine the device status based on services.
          System.out.println("BatchGetDeviceState detection:" + ds.getDeviceName() + "The device is offline.");
        }
      }
    } else {
      System.out.println("BatchGetDeviceState detection:" + "The API call fails. The device" + deviceName + "may not exist.");
    }
  }

  /**
   * Queries the details of a single device.
   * QueryDeviceDetail https://help.aliyun.com/document_detail/69594.html
   * 
   * @param client // The client that sends a request to the server.
   * @throws ServerException
   * @throws ClientException
   */
  public void ByQueryDeviceDetail(DefaultAcsClient client) throws ServerException, ClientException {

    // Fills in the request.
    QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
    request.setProductKey(productKey); // The unique identifier of the product to which the target device belongs.
    request.setDeviceName(deviceName); // The name of the target device.

    // Obtains a response.
    QueryDeviceDetailResponse response = (QueryDeviceDetailResponse) client.getAcsResponse(request);
    if (response ! = null && response.getSuccess()) {
      QueryDeviceDetailResponse.Data data = response.getData();
      // ONLINE: The device is online.
      // OFFLINE: The device is offline.
      // UNACTIVE: The device is inactive.
      // DISABLE: The device is disabled.
      if ("ONLINE".equals(data.getStatus())) {
        System.out.println("QueryDeviceDetail detection:" + deviceName + "The device is online.");
      } else { // Other states are considered that the device is offline. You can also determine the device status based on services.
        System.out.println("QueryDeviceDetail detection:" + deviceName + "The device is offline.");
      }
    } else {
      System.out.println("QueryDeviceDetail detection:" + "The API call fails. The device" + deviceName + "may not exist.");
    }
  }

  /**
   * Queries the details of devices in batches.
   * BatchQueryDeviceDetail https://help.aliyun.com/document_detail/123470.html
   * 
   * @param client // The client that sends a request to the server.
   * @throws ServerException
   * @throws ClientException
   */
  public void ByBatchQueryDeviceDetail(DefaultAcsClient client) throws ServerException, ClientException {

    // Fills in the request.
    BatchQueryDeviceDetailRequest request = new BatchQueryDeviceDetailRequest();
    request.setProductKey(productKey); // The unique identifier of the product to which the target device belongs.
    List<String> deviceNames = new ArrayList<String>(); // A list of target device names.
    deviceNames.add(deviceName);
    request.setDeviceNames(deviceNames);

    // Obtains a response.
    BatchQueryDeviceDetailResponse response = (BatchQueryDeviceDetailResponse) client.getAcsResponse(request);
    if (response ! = null && response.getSuccess()) {
      List<DataItem> diList = response.getData();
      for (DataItem di : diList) {
        // ONLINE: The device is online.
        // OFFLINE: The device is offline.
        // UNACTIVE: The device is inactive.
        // DISABLE: The device is disabled.
        if ("ONLINE".equals(di.getStatus())) {
          System.out.println("BatchQueryDeviceDetail detection:" + di.getDeviceName() + "The device is online.");
        } else { // Other states are considered that the device is offline. You can also determine the device status based on services.
          System.out.println("BatchQueryDeviceDetail detection:" + di.getDeviceName() + "The device is offline.");
        }
      }
    } else {
      System.out.println("BatchQueryDeviceDetail detection:" + "The API call fails. The device" + deviceName + "may not exist.");
    }
  }

  /**
   * Uses RRPC to check the device status.
   * RRpc https://help.aliyun.com/document_detail/69797.html
   * 
   * @param client // The client that sends a request to the server.
   * @throws ServerException
   * @throws ClientException
   */
  public void ByRRpc(DefaultAcsClient client) throws ServerException, ClientException {

    // Fills in the request.
    RRpcRequest request = new RRpcRequest();
    request.setProductKey(productKey); // The unique identifier of the product to which the target device belongs.
    request.setDeviceName(deviceName); // The name of the target device.
    request.setRequestBase64Byte(Base64.encodeBase64String("Hello World".getBytes())); // Message content, which must be a Base64-encoded string.
    request.setTimeout(5000); // Response time-out period, which can be set as needed.

    // Obtains a response.
    RRpcResponse response = (RRpcResponse) client.getAcsResponse(request);
    if (response ! = null) { // Do not use response.getSuccess() to determine the device status. The result "false" is returned if the operation result is not "SUCCESS". Always determine the device status based on RrpcCode.
      // UNKNOWN: A system exception occurred.
      // SUCCESS: The operation is successful.
      // TIMEOUT: Waiting for device response times out.
      // OFFLINE: The device is offline.
      // HALFCONN: The device is offline. In this state, the device is offline but this does not last for a full heartbeat cycle.
      if ("SUCCESS".equals(response.getRrpcCode())) {
        System.out.println("RRPC detection:" + deviceName + "The device is online.");
      } else if (response.getRrpcCode() == null) {
        System.out.println("RRPC detection:" + deviceName + "The device may not exist.");
      } else { // Other states are considered that the device is offline. You can also determine the device status based on services.
        System.out.println("RRPC detection:" + deviceName + "The device is offline.");
      }
      // RRPC also provides more complex methods of device status detection.
      // For more information, see https://help.aliyun.com/document_detail/101133.html.
    } else {
      System.out.println("RRPC detection:" + "The API call fails.");
    }
  }
}

For more details, refer to the official product documentation.

0 0 0
Share on

GXIC

25 posts | 3 followers

You may also like

Comments

GXIC

25 posts | 3 followers

Related Products

  • IoT Platform

    Provides secure and reliable communication between devices and the IoT Platform which allows you to manage a large number of devices on a single IoT Platform.

    Learn More
  • IoT Solution

    A cloud solution for smart technology providers to quickly build stable, cost-efficient, and reliable ubiquitous platforms

    Learn More
  • Intelligent Robot

    A dialogue platform that enables smart dialog (based on natural language processing) through a range of dialogue-enabling clients

    Learn More