You can use the HTTP/2 SDK for Java to establish connections between your devices and IoT Platform. This article provides an SDK demo for Java. You can refer to this demo to develop an SDK and upload device messages to IoT Platform.
Prerequisites
A Maven project is used in the SDK demo for Java. Before you begin, make sure that you have installed Maven.
Procedure
- Download the HTTP/2 SDK demo for Java iot-http2-sdk-demo.
- Use IntelliJ IDEA or Eclipse to import the demo into your Maven project.
- Obtain the certificate information of a device from the IoT Platform console. For more information, see Create products and devices in User Guide.
- Modify the H2Client.java configuration file.
- Configure the parameters.
// Obtain the ProductKey, DeviceName, and DeviceSecret of the device from the IoT Platform console. String productKey = ""; String deviceName = ""; String deviceSecret = ""; // The topics that are used to receive and send messages. String subTopic = "/" + productKey + "/" + deviceName + "/get"; String pubTopic = "/" + productKey + "/" + deviceName + "/update";
- Connect the HTTP/2 SDK to the HTTP/2 server and configure data receiving.
// endPoint: https://${YourProductKey}.iot-as-http2.${region}.aliyuncs.com String endPoint = "https://" + productKey + ".iot-as-http2.cn-shanghai.aliyuncs.com"; // The unique identifier of the client device. String clientId = InetAddress.getLocalHost().getHostAddress(); // Configure connection parameters. Profile profile = Profile.getDeviceProfile(endPoint, productKey, deviceName, deviceSecret, clientId); // If the value is true, all messages that are sent when the device is offline are deleted. Offline messages refer to all QoS=0 or QoS=1 messages that are not received. profile.setCleanSession(false); // Construct the client. MessageClient client = MessageClientFactory.messageClient(profile); // Receive data. client.connect(messageToken -> { Message m = messageToken.getMessage(); System.out.println("receive message from " + m); return MessageCallback.Action.CommitSuccess; });
- Subscribe to topics.
// Subscribe to a topic. After the HTTP/2 SDK is connected to IoT Platform, the HTTP/2 SDK can receive messages from the specified topic in a callback. CompletableFuture subFuture = client.subscribe(subTopic); System.out.println("sub result : " + subFuture.get());
- Send data.
// Publish a message. MessageToken messageToken = client.publish(pubTopic, new Message("hello iot".getBytes(), 0)); System.out.println("publish success, messageId: " + messageToken.getPublishFuture().get().getMessageId());
- Configure the parameters.
- Run the code after you have modified the configuration file.
Operation descriptions
- Identity authentication
To connect a device to IoT Platform, you must use Profile to configure identity information and other relevant parameters of the device. The following sample code describes how to configure the operation parameters:
Profile profile = Profile.getDeviceProfile(endPoint, productKey, deviceName, deviceSecret, clientId); MessageClient client = MessageClientFactory.messageClient(profile); client.connect(messageToken -> { Message m = messageToken.getMessage(); System.out.println("receive message from " + m); return MessageCallback.Action.CommitSuccess; });
Parameters in Profile
Parameter Type Required Description endPoint String Yes The endpoint, in the format of https://${YourProductKey}.iot-as-http2.${regionId}.aliyuncs.com
.- Replace ${YourProductKey} with your product key.
- Replace ${regionId} with the ID of the region where you purchased the IoT Platform service. For more information about region IDs, see Regions and zones.
productKey String Yes The key of the product to which the device belongs. You can obtain this information from the IoT Platform console. deviceName String Yes The name of the device. You can obtain this information from the IoT Platform console. deviceSecret String Yes The key of the device. You can obtain this information from the IoT Platform console. clientId String Yes The unique identifier of the client device. cleanSession Boolean No Indicates whether to delete cached messages that are sent when the device is offline. heartBeatInterval Long No The heartbeat interval, in milliseconds. heartBeatTimeOut Long No The heartbeat timeout time, in milliseconds. multiConnection Boolean No Indicates whether to enable multi-connections. If the ProductKey and DeviceName of the device are used to connect to IoT Platform, set this parameter to false. callbackThreadCorePoolSize Integer No The size of the core pool for the callback thread. callbackThreadMaximumPoolSize Integer No The maximum number of threads for the callback thread pool. callbackThreadBlockingQueueSize Integer No The size of the blocking queue for the callback thread pool. authParams Map No The custom authentication parameters. - Connection establishment
After MessageClient is generated, call the connection establishment operation to connect the device to IoT Platform. The device can send messages to IoT Platform and receive messages from IoT Platform only after the device passes identity authentication. After the connection is established, the server immediately pushes the subscribed messages to the HTTP/2 SDK. Therefore, when you establish a connection, you must configure the default message receiving operation to receive messages for which no callback is configured. The following sample code describes the connection establishment operation:
void connect(MessageCallback messageCallback);
- Message subscription
/** * Subscribe to a topic. * @param topic topic * @return completableFuture for subscribe result */ CompletableFuture subscribe(String topic); /** * Subscribe to a topic and specify the callback for the topic. * @param topic topic * @param messageCallback callback when message is received on this topic * @return completableFuture for subscribe result */ CompletableFuture subscribe(String topic, MessageCallback messageCallback); /** * Unsubscribe from the topic. * * @param topic topic * @return completableFuture for unsubscribe result */ CompletableFuture unsubscribe(String topic);
- Message receiving
Before you configure message receiving, you must configure the MessageCallback operation. Additionally, you must pass in MessageClient when you configure connection parameters or subscribe to a topic. The following sample code describes the message receiving operation:
/** * * @param messageToken message token * @return Action action after consuming */ Action consume(final MessageToken messageToken);
This operation is called after the HTTP/2 SDK receives messages by calling MessageToken.getMessage. Operations are called in the thread pool. Pay attention to security issues of the threads. The return values determine whether to return ACKs for QoS=0 and QoS=1 messages. The following table describes the return values.
Return value Description Action.CommitSuccess An ACK will be returned. Action.CommitFailure No ACK will be returned. The HTTP/2 SDK will receive the message again later. Action.CommitAckManually An ACK will not be automatically returned. You must call MessageClient.ack() to manually return an ACK. - Message sending
/** * Publish a message to the specified topic. * * @param topic message topic * @param message message entity * @return completableFuture for publish result */ MessageToken publish(String topic, Message message);