Updated on 2024-04-29 GMT+08:00

Message Reporting Example

Introduction

This section describes how to use Java SDKs for the development of message reporting.

Development Environment Requirements

JDK 1.8 or later has been installed.

Configuring the SDK on Devices

  1. Download an SDK.
  2. Configure the Maven dependency of the SDK on devices.
    <dependency>
    	<groupId>com.huaweicloud</groupId>
    	<artifactId>iot-device-sdk-java</artifactId>
    	<version>1.1.4</version>
    </dependency>
  3. Configure the SDK and device connection parameters on devices.
    // Load the CA certificate of the IoT platform. For details about how to obtain the certificate, visit https://support.huaweicloud.com/intl/en-us/devg-iothub/iot_02_1004.html#section3.
    URL resource = BroadcastMessageSample.class.getClassLoader().getResource("ca.jks");
    File file = new File(resource.getPath());
    
    // The format is ssl://Domain name:Port number.
    // To obtain the domain name, log in to the Huawei Cloud IoTDA console. In the navigation pane, choose Overview and click Access Details in the Instance Information area. Select the access domain name corresponding to port 8883.
    String serverUrl = "ssl://localhost:8883";
    // Device ID created on the IoT platform
    String deviceId = "deviceId";
    // Secret corresponding to the device ID
    String deviceSecret = "secret";
    // Create a device.
    IoTDevice device = new IoTDevice(serverUrl, deviceId, deviceSecret, file);
    if (device.init() != 0) {
        return;
    }
  4. Report a device message.
    device.getClient().reportDeviceMessage(new DeviceMessage("hello"), new ActionListener() {
        @Override        
        public void onSuccess(Object context) {             
            log.info("reportDeviceMessage success: ");
        }          
        @Override        
        public void onFailure(Object context, Throwable var2) {
            log.error("reportDeviceMessage fail: "+var2);         
        }     
    });

Testing and Verification

  • On the IoTDA console, choose Devices > All Devices. Select a device to access its details page, and click Start Trace on the Message Trace tab page.
  • Run the SDK code on the device. The following is an example of the log format when the device reports a message.
    Figure 1 Java SDK message reporting result log
  • Check the result on the Message Trace tab page.
    Figure 2 Message tracing of the message reporting process