El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Java Demo Usage Guide

Updated on 2024-12-31 GMT+08:00

Overview

This topic uses Java as an example to describe how to connect a device to the platform over MQTTS or MQTT and how to use platform APIs to report properties and subscribe to a topic for receiving commands.

NOTE:

The code snippets in this document are only examples and are for trial use only. To put them into commercial use, obtain the IoT Device SDKs of the corresponding language for integration by referring to Obtaining Resources.

Prerequisites

Preparations

Installing IntelliJ IDEA

  1. Go to the IntelliJ IDEA website to download and install a desired version. The following uses Windows 64-bit IntelliJ IDEA 2019.2.3 Ultimate as an example.

  2. After the download is complete, run the installation file and install IntelliJ IDEA as prompted.

Importing Sample Code

  1. Download the Java demo.
  2. Open the IDEA developer tool and click Import Project.

  3. Select the downloaded Java demo and click Next.

  4. Import the sample code.

Establishing a Connection

To connect a device or gateway to the platform, upload the device information to bind the device or gateway to the platform.

  1. Before establishing a connection, modify the following parameters:
    1
    2
    3
    4
    5
    // MQTT connection address of the platform. Replace it with the domain name of the IoT platform that the device is connected to.
    static String serverIp = "xxx.myhuaweicloud.com";
    // Device ID and secret obtained during device registration (Replace them with the actual values.)
    static String deviceId = "722cb****************";
    static String secret = "******";
    
    • serverIp indicates the device connection address of the platform. To obtain this address, see Platform Connection Information. (After obtaining the domain name, run the ping Domain name command in the CLI to obtain the corresponding IP address.)
    • deviceId and secret indicate the device ID and secret, which can be obtained after the device is registered.
  2. Use MqttClient to set up a connection. The recommended heartbeat interval for MQTT connections is 120 seconds. For details, see Constraints.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(false);
    options.setKeepAliveInterval(120); // Set the heartbeat interval from 30 to 1200 seconds.
    options.setConnectionTimeout(5000);
    options.setAutomaticReconnect(true);
    options.setUserName(deviceId);
    options.setPassword(getPassword().toCharArray());
    client = new MqttAsyncClient(url, getClientId(), new MemoryPersistence());
    client.setCallback(callback);
    

    Port 1883 is a non-encrypted MQTT access port, and port 8883 is an encrypted MQTTS access port (that uses SSL to load a certificate).

    1
    2
    3
    4
    5
    if (isSSL) {
        url = "ssl://" + serverIp + ":" + 8883; // MQTTS connection
    } else {
        url = "tcp://" + serverIp + ":" + 1883; // MQTT connection
    }
    
    To establish an MQTTS connection, load the SSL certificate of the server and add the SocketFactory parameter. The DigiCertGlobalRootCA.jks file is stored in the resources directory of the demo. It is used by the device to verify the platform identity when the device connects to the platform. You can download the certificate file using the link provided in Certificates.
    1
    options.setSocketFactory(getOptionSocketFactory(MqttDemo.class.getClassLoader().getResource("DigiCertGlobalRootCA.jks").getPath()));
    
  3. Call client.connect(options, null, new IMqttActionListener()) to initiate a connection. The MqttConnectOptions parameter is passed.
    1
    client.connect(options, null, new IMqttActionListener()
    
  4. The password passed by calling options.setPassword() is encrypted during creation of MqttConnectOptions. getPassword() is used to obtain the encrypted password.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    public static String getPassword() {
        return sha256_mac(secret, getTimeStamp());
    }
    /* Call the SHA-256 algorithm for hash calculation. */
    public static String sha256_mac(String message, String tStamp) {    
        String passWord = null;
        try {        
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");        
            SecretKeySpec secret_key = new SecretKeySpec(tStamp.getBytes(), "HmacSHA256");        
            sha256_HMAC.init(secret_key);byte[] bytes = sha256_HMAC.doFinal(message.getBytes());        
            passWord = byteArrayToHexString(bytes);    
        } catch (Exception e) {
            e.printStackTrace();    
        }
        return passWord;
    
  5. After the connection is established, the device becomes online.
    Figure 1 Device list - Device online status

    If the connection fails, the onFailure function executes backoff reconnection. The example code is as follows:

    @Override
    public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
        System.out.println("Mqtt connect fail.");
    
        // Backoff reconnection
        int lowBound = (int) (defaultBackoff * 0.8);
        int highBound = (int) (defaultBackoff * 1.2);
        long randomBackOff = random.nextInt(highBound - lowBound);
        long backOffWithJitter = (int) (Math.pow(2.0, (double) retryTimes)) * (randomBackOff + lowBound);
        long waitTImeUntilNextRetry = (int) (minBackoff + backOffWithJitter) > maxBackoff ? maxBackoff : (minBackoff + backOffWithJitter);
        System.out.println("----  " + waitTImeUntilNextRetry);
        try {
            Thread.sleep(waitTImeUntilNextRetry);
            } catch (InterruptedException e) {
                System.out.println("sleep failed, the reason is" + e.getMessage().toString());
            }
            retryTimes++;
            MqttDemo.this.connect(true);
    }

Subscribing to a Topic for Receiving Commands

Only devices that subscribe to a specific topic can receive messages about the topic published by the broker. For details on the preset topics, see Topics. For details about the API, see Platform Delivering a Command.

1
2
// Subscribe to a topic for receiving commands.
client.subscribe(getCmdRequestTopic(), qosLevel, null, new IMqttActionListener();
getCmdRequestTopic() is used to obtain the topic for receiving commands from the platform and subscribe to the topic.
1
2
3
public static String getCmdRequestTopic() {
    return "$oc/devices/" + deviceId + "/sys/commands/#";
}

Reporting Properties

Devices can report their properties to the platform. For details, see Reporting Device Properties.

1
2
3
4
// Report JSON data. service_id must be the same as that defined in the product model.
String jsonMsg = "{\"services\": [{\"service_id\": \"Temperature\",\"properties\": {\"value\": 57}},{\"service_id\": \"Battery\",\"properties\": {\"level\": 80}}]}";
MqttMessage message = new MqttMessage(jsonMsg.getBytes());
client.publish(getRreportTopic(), message, qosLevel, new IMqttActionListener();

The message body jsonMsg is assembled in JSON format, and service_id must be the same as that defined in the product model. properties indicates a device property, and 57 indicates the property value. event_time indicates the UTC time when the device reports data. If this parameter is not specified, the system time is used by default.

After a device or gateway is connected to the platform, you can call MqttClient.publish(String topic,MqttMessage message) to report device properties to the platform.

getRreportTopic() is used to obtain the topic for reporting data.
1
2
3
public static String getRreportTopic() {
    return "$oc/devices/" + deviceId + "/sys/properties/report";
}

Viewing Reported Data

After the main method is called, you can view the reported device property data on the device details page. For details about the API, see Device Reporting Properties.

Figure 2 Viewing reported data - level
Figure 3 Viewing reported data - temperature_value
NOTE:

If no latest data is displayed on the device details page, modify the services and properties in the product model to ensure that the reported services and properties are the same as those defined in the product model. Alternatively, go to the product details page and delete all services.

Related Resources

You can refer to the MQTT or MQTTS API Reference on the Device Side to connect MQTT devices to the platform. You can also develop an MQTT-based smart street light online to quickly verify whether they can interact with the IoT platform to publish or subscribe to messages.

NOTE:

Synchronous commands require device responses. For details, see Upstream Response Parameters.

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback