หน้านี้ยังไม่พร้อมใช้งานในภาษาท้องถิ่นของคุณ เรากำลังพยายามอย่างหนักเพื่อเพิ่มเวอร์ชันภาษาอื่น ๆ เพิ่มเติม ขอบคุณสำหรับการสนับสนุนเสมอมา

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

Node.js Demo Usage Guide

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

Overview

This topic uses Node.js 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

  1. Go to the Node.js website to download and install a desired version. The following uses Windows 64-bit and Node.js v12.18.0 (npm 6.14.4) as an example.

  2. After the download is complete, run the installation file and install Node.js as prompted.
  3. Verify that the installation is successful.

    Press Win+R, enter cmd, and press Enter. The command-line interface (CLI) is displayed.

    Enter node -v and press Enter. The Node.js version is displayed. Enter npm -v. If any version information is displayed, the installation is successful.

Importing Sample Code

  1. Download the sample code quickStart(Node.js) and decompress the package.
  2. Press Win+R, enter cmd, and press Enter to open the CLI. Run the following commands to install the global module:

    npm install mqtt -g: This command is used to install the MQTT protocol module.

    npm install crypto-js -g: This command is used to install the device secret cryptographic algorithm module.

    npm install fs -g: This command is used to load the platform certificate.

  3. Find the directory where the package is decompressed.

    Code directory:
    • DigiCertGlobalRootCA.crt.pem: platform certificate file
    • MqttDemo.js: Node.js source code for MQTT or MQTTS connection to the platform, property reporting, and command delivery.

  4. Set the project parameters in the demo. In MqttDemo.js, set the server address, device ID, and device secret for connecting to the device registered on the console when the demo is started.

    var TRUSTED_CA = fs.readFileSync("DigiCertGlobalRootCA.crt.pem");// Obtain a certificate.
    
    // MQTT connection address of the platform. Replace it with the domain name of the IoT platform that the device is connected to.
    var serverUrl = "xxx.myhuaweicloud.com"; // Enter the access address of the platform that the device is connected to.
    
    // Device ID and secret obtained during device registration (Replace them with the actual values.)
    var deviceId = "722cb****************";
    var secret = "****";
    var timestamp = dateFormat("YYYYmmddHH", new Date());
    
    var propertiesReportJson = {'services':[{'properties':{'alarm':1,'temperature':12.670784,'humidity':18.37673,'smokeConcentration':19.97906},'service_id':'smokeDetector','event_time':null}]};
    var responseReqJson = {'result_code': 0,'response_name': 'COMMAND_RESPONSE','paras': {'result': 'success'}};

  5. Select different options from mqtt.connect(options) to determine whether to perform SSL encryption during connection establishment on the device. You are advised to use the default MQTTS connection.

    // MQTTS connection
    var options = {
        host: serverUrl,
        port: 8883,
        clientId: getClientId(deviceId),
        username: deviceId,
        password:HmacSHA256(secret, timestamp).toString(),
        ca: TRUSTED_CA,
        protocol: 'mqtts',
        rejectUnauthorized: false,
        keepalive: 120,
        reconnectPeriod: 10000,
        connectTimeout: 30000
    }
    
    // MQTT connection is insecure and is not recommended.
    var option = {
        host: serverUrl,
        port: 1883,
        clientId: getClientId(deviceId),
        username: deviceId,
        password: HmacSHA256(secret, timestamp).toString(),
        keepalive: 120,
        reconnectPeriod: 10000,
        connectTimeout: 30000
        //protocol: 'mqtts'
        //rejectUnauthorized: false
    }
    
    // By default, options is used for secure connection.
    var client = mqtt.connect(options);

Starting the Demo

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

  1. This demo provides methods such as establishing an MQTT or MQTTS connection. By default, MQTT uses port 1883, and MQTTS uses port 8883. (In the case of MQTTS connections, you must load the certificate for verifying the platform identity. The certificate is used for login authentication when the device connects to the platform.) Call the mqtt.connect(options) method to establish an MQTT connection.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var client = mqtt.connect(options);
    
    client.on('connect', function () {
        log("connect to mqtt server success, deviceId is " + deviceId);
        // Subscribe to a topic.
        subScribeTopic();
        // Publish a message.
        publishMessage();
    })
    
    // Respond to the command.
    client.on('message', function (topic, message) {
        log('received message is ' + message.toString());
    
        var jsonMsg = responseReq;
        client.publish(getResponseTopic(topic.toString().split("=")[1]), jsonMsg);
        log('responsed message is ' + jsonMsg);
    })
    

    Find the Node.js demo source code directory, modify key project parameters, and start the demo.

    Before the demo is started, the device is in the offline state.

    Figure 1 Device List - Device offline

    After the demo is started, the device status changes to online.

    Figure 2 Device list - Device online status

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

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    client.on('reconnect', () => {
    
        log("reconnect is starting");
    	
        // Backoff reconnection
        var lowBound = Number(defaultBackoff)*Number(0.8);
        var highBound = Number(defaultBackoff)*Number(1.2);
    	
        var randomBackOff = parseInt(Math.random()*(highBound-lowBound+1),10);
    	
        var backOffWithJitter = (Math.pow(2.0, retryTimes)) * (randomBackOff + lowBound);
    	
        var waitTImeUtilNextRetry = (minBackoff + backOffWithJitter) > maxBackoff ? maxBackoff : (minBackoff + backOffWithJitter);
    	
        client.options.reconnectPeriod = waitTImeUtilNextRetry;
    	
        log("next retry time: " + waitTImeUtilNextRetry);
    	
        retryTimes++;
    })
    
  2. 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. This demo calls the subScribeTopic method to subscribe to a topic. After the subscription is successful, wait for the platform to deliver a command.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    // Subscribe to a topic for receiving commands.
    function subScribeTopic() {
        client.subscribe(getCmdRequestTopic(), function (err) {
            if (err) {
                log("subscribe error:" + err);
            } else {
                log("topic : " + getCmdRequestTopic() + " is subscribed success");
            }
        })
    }
    
  3. Publishing a topic means that a device proactively reports its properties or messages to the platform. For details, see the API Device Reporting Properties. After the connection is successful, call the publishMessage method to report properties.
    1
    2
    3
    4
    5
    6
    7
    8
    // Report JSON data. serviceId must be the same as that defined in the product model.
    function publishMessage() {
        var jsonMsg = propertiesReport;
        log("publish message topic is " + getReportTopic());
        log("publish message is " + jsonMsg);
        client.publish(getReportTopic(), jsonMsg);
        log("publish message successful");
    }
    
    Reported properties in the JSON format are as follows:
    1
    var propertiesReportJson = {'services':[{'properties':{'alarm':1,'temperature':12.670784,'humidity':18.37673,'smokeConcentration':19.97906},'service_id':'smokeDetector','event_time':null}]};
    

    The following figure shows the CLI.

    If the properties are reported, the following information is displayed on the IoTDA console:

    Figure 3 Viewing reported data - Demo_smokeDetector
    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.

Receiving a Command

The demo provides the method for receiving commands delivered by the platform. After an MQTT connection is established and a topic is subscribed, you can deliver a command on the device details page of the IoTDA console or by using the demo on the application side. After the command is delivered, the MQTT callback function receives the command delivered by the platform.

For example, deliver a command carrying the parameter name smokeDetector: SILENCE and parameter value 50.

Figure 4 Command delivery - SILENCE

After the command is delivered, the demo receives a 50 message. The following figure shows the command execution page.

NOTE:

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

เราใช้คุกกี้เพื่อปรับปรุงไซต์และประสบการณ์การใช้ของคุณ การเรียกดูเว็บไซต์ของเราต่อแสดงว่าคุณยอมรับนโยบายคุกกี้ของเรา เรียนรู้เพิ่มเติม

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback