Using Service Subscription (HTTP/2) to Retrieve Device Status

Image for post
Image for post

Several service scenarios of the Internet of Things (IoT) require the real-time status of devices for state-specific (online or offline) processing. Alibaba Cloud IoT Platform provides the service subscription function to retrieve the device status.

Principle

To track the real-time status of the IoT devices, configure the function of receiving device status-change notifications through service subscription in the IoT Platform console. Subsequently, the IoT Platform pushes device online and offline messages for the specific product to the respective server. The server receives device status change notifications by using the HTTP/2 SDK. The following flowchart shows the complete process.

Image for post
Image for post

Note: In Steps 1.1 and 2.1, the IoT Platform determines whether the console is configured with the function of receiving device status-change notifications through service subscription.

The following code shows the data format of notification messages about device status changes.

"status":"online|offline",
"productKey":"al123455****",
"deviceName":"deviceName1234",
"time":"2018-08-31 15:32:28.205",
"utcTime":"2018-08-31T07:32:28.205Z",
"lastTime":"2018-08-31 15:32:28.195",
"utcLastTime":"2018-08-31T07:32:28.195Z",
"clientIp":"123.123. ***. ***"
}

Subscription

In the IoT Platform console, configure the function of receiving device status-change notifications through HTTP/2 service subscription by implementing the following steps.

1) Log on to the IoT Platform console.
2) In the left-side navigation pane, choose Devices > Products.
3) In the product list, find the product for which you want to configure service subscription and click the View button for this product.
4) On the Product Details page, choose Service Subscription > Set.
5) Select Device Status Change Notification for Configure Service Subscription and click Save.

Reception

The server receives device status-change notifications by using the HTTP/2 SDK. This example shows how to configure the Java HTTP/2 SDK.

Description: Only JDK 8 is supported.

If the same Alibaba Cloud account is used to start multiple HTTP/2 SDKs, the IoT Platform randomly sends device status-change notifications to one of the clients.

In the Maven project, add the following pom dependency to install Alibaba Cloud IoT SDK:

<groupId>com.aliyun.openservices</groupId>
<artifactId>iot-client-message</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.7.1</version>
</dependency>

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

private static String accessKeyID = "Config.accessKey";
// The AccessKey Secret of your Alibaba Cloud account.
private static String accessKeySecret = "Config.accessKeySecret";
// The AccessKey ID of your Alibaba Cloud account.
private static String uid = "Config.uid";
// The region ID of your IoT Platform service.
private static String regionId = "cn-shanghai";
// endPoint: https://${uid}.iot-as-http2.${region}.aliyuncs.com
private static String endPoint = "https://" + uid + ".iot-as-http2." + regionId + ".aliyuncs.com";

Refer to the following Sample Code.

* Copyright © 2019 Alibaba. All rights reserved.
*/
package com.aliyun.iot.demo.checkstatus;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.iot.api.Profile;
import com.aliyun.openservices.iot.api.message.MessageClientFactory;
import com.aliyun.openservices.iot.api.message.api.MessageClient;
import com.aliyun.openservices.iot.api.message.callback.MessageCallback;
import com.aliyun.openservices.iot.api.message.entity.MessageToken;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
public class GetDeviceStatusByH2 { // ===================The list of required parameters begins here===========================
// Set Config. * parameters based on your account information.
// For more information about how to obtain the values of required parameters, see https://help.aliyun.com/document_detail/89227.html.
// The AccessKey ID and AccessKey secret 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";
// Your UID.
private static String uid = "Config.uid";
// The region ID of your IoT Platform service.
private static String regionId = "cn-shanghai";
// endPoint: https://${uid}.iot-as-http2.${region}.aliyuncs.com
private static String endPoint = "https://" + uid + ".iot-as-http2." + regionId + ".aliyuncs.com";
// ===================The list of required parameters ends here===========================
private static ExecutorService executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("http2-downlink-handle-%d").build(),
new ThreadPoolExecutor.AbortPolicy());
/**
* 1. Configure service subscription.
* 2. Start the program.
* 3. Start your device to make it go online.
* 4. Shut down your device to make it go offline.
* 5. View the log output by the program.
*
* @param args
*/
public static void main(String[] args) {
// Configures the connection.
Profile profile = Profile.getAccessKeyProfile(endPoint, regionId, accessKeyID, accessKeySecret);
// Constructs a client.
MessageClient client = MessageClientFactory.messageClient(profile);
// Processes message callback.
MessageCallback messageCallback = new MessageCallback() {
@Override
public Action consume(MessageToken messageToken) {
// Returns the result that indicates successful consumption and starts a new thread to avoid callback blocking.
executorService.submit(() -> handleDownLinkMessage(messageToken));
// Returns commitSuccess soon after message reception.
return MessageCallback.Action.CommitSuccess;
}
};
// Filters data locally. IoT Platform pushes all subscribed device messages and filters out target messages by topic matching.
// Processes only the messages with a topic starting with /as/mqtt/status. Other received messages are ignored.
// For more information about topics and message formats, see https://help.aliyun.com/document_detail/73736.html.
client.setMessageListener("/as/mqtt/status/#", messageCallback);
// Performs a generic callback to process the unmatched messages in setMessageListener.
MessageCallback messageCallbackCommon = new MessageCallback() {
@Override
public Action consume(MessageToken messageToken) {
// Starts a new thread for processing if necessary.
return MessageCallback.Action.CommitSuccess;
}
};
// Receives data.
client.connect(messageCallbackCommon);
}
private static void handleDownLinkMessage(MessageToken messageToken) {
// The message body is in JSON format.
String message = new String(messageToken.getMessage().getPayload());
// Retrieves the status field that indicates the device online status.
JSONObject json = (JSONObject) JSON.parse(message);
String deviceName = json.getString("deviceName");
String status = json.getString("status");
System.out.println("Original message content: " + message);
System.out.println(deviceName + "Online status: " + status);
// Other custom implementations.
}
}

Original Source:

Written by

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store