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

Command Delivery

Overview

A product model defines commands that can be delivered to the devices. Applications can call platform APIs to deliver commands to the devices to effectively manage these devices.

IoTDA supports synchronous and asynchronous command delivery.

Table 1 Command delivery

Mechanism

Description

Scenario

Devices Using LwM2M over CoAP

Devices Using MQTT

Synchronous command delivery

An application calls the synchronous command delivery API to deliver a command to a specified device for device control. The platform sends the command to the device and returns the command execution result in an HTTP request to the application. If the device does not respond, the platform returns a timeout message to the application.

Applicable to commands that must be executed in real time, for example, turning on a street lamp or closing a gas meter switch. Applications should determine the appropriate time to deliver a command.

Not applicable

Applicable

Asynchronous command delivery

An application calls the asynchronous command delivery API to deliver a command to a specified device for device control. The platform sends the command to the device and asynchronously pushes the command execution result to the application.

Asynchronous command delivery is classified into immediate delivery and delayed delivery.

  • In immediate delivery, the platform delivers commands to a device regardless of whether the device is online. If the device is offline or the device does not receive the command, the delivery fails.
  • In delayed delivery, the platform caches a command and delivers it to a device when the device goes online or reports data. If a device has multiple pending commands, the platform delivers the commands in sequence.
  • Immediate delivery applies to scenarios with high real-time requirements.
  • Delayed delivery applies to commands that do not need to be executed immediately, for example, configuring water meter parameters.

Applicable

Not applicable

Scenarios

  • Synchronous delivery applies to scenarios that require real-time command delivery. Asynchronous delivery is used for device control.
  • Data needs to be forwarded to other Huawei Cloud services for storage and processing based on data forwarding rules.

Constraints

  • Max. size of a single message: 256 KB.
  • Product models are required.
  • Devices need to respond to the synchronous command within 20 seconds.
  • Up to 20 asynchronous commands can be cached at a time.
  • Max. cache duration (configurable): 48 hours.

Synchronous Command Delivery

You can deliver synchronous commands to MQTT devices one by one or in batches.

Table 2 Synchronous command delivery

Type

Description

Scenario

Example

Synchronous command delivery to a single MQTT device

IoTDA delivers a control command to a single device.

The function is used to deliver a control command to a single device.

Synchronous Command Delivery to an Individual MQTT Device

Synchronous command delivery to a batch of MQTT devices

IoTDA delivers control commands to devices in batches. You can create a batch task to perform operations on multiple devices at a time.

The function is used to deliver control commands to devices in batches.

Synchronous Command Delivery to a Batch of MQTT Devices

Synchronous Command Delivery to an Individual MQTT Device

For details on how to set and query properties, see instructions of the APIs for querying device properties and modifying device properties.

Figure 1 Command delivery process
  1. An application calls the API for delivering a command to a device to send a command to the platform. Example message:
    POST https://{Endpoint}/v5/iot/{project_id}/devices/{device_id}/commands
    Content-Type: application/json
    X-Auth-Token: ********
    
    {
      "service_id" : "WaterMeter",
      "command_name" : "ON_OFF",
      "paras" : {
        "value" : "ON"
      }
    }
  2. The platform sends the command to the device according to the protocol specifications. Example message:
    Topic: $oc/devices/{device_id}/sys/commands/request_id={request_id} 
    Data format:
    {
      "object_device_id": "{object_device_id}",
      "command_name": "ON_OFF",
      "service_id": "WaterMeter",
      "paras": {
        "value": "ON"
      }
    }
  3. After executing the command, the device returns the command execution result through the API for delivering a command. Example message:
    Topic: $oc/devices/{device_id}/sys/commands/response/request_id={request_id}
    Data format:
    {
        "result_code": 0,
        "response_name": "COMMAND_RESPONSE",
        "paras": {
            "result": "success"
        }
    }
  4. The platform synchronously sends a response to the HTTP command. Example message:
    Status Code: 200 OK
    Content-Type: application/json
    
    {
      "command_id" : "b1224afb-e9f0-4916-8220-b6bab568e888",
      "response" : {
        "result_code" : 0,
        "response_name" : "COMMAND_RESPONSE",
        "paras" : {
          "result" : "success"
        }
      }
    }

Synchronous Command Delivery to a Batch of MQTT Devices

The API for creating a batch task can be used to deliver a command to multiple MQTT devices. The following describes how to call the API for creating a batch task to deliver commands in batches.

  1. An application calls the API for creating a batch task to send a command to the platform. Example message:
    POST https://{Endpoint}/v5/iot/{project_id}/batchtasks 
    Content-Type: application/json
    X-Auth-Token: ********
    {
      "app_id": "********",
      "task_name": "task123",
      "task_type": "createCommands",
      "targets": [
        "********",
        "********"
      ],
      "document": {
        "service_id": "water",
        "command_name": "ON_OFF",
        "paras": {
          "value": "ON"
        }
      }
    }
    Table 3 Parameters for creating a batch task of command delivery

    Parameter

    Mandatory

    Description

    app_id

    No

    Resource space ID.

    task_name

    Yes

    Custom task name.

    task_type

    Yes

    Type of the batch task. For details, see Create a Batch Task. Options:

    • createCommands: task for creating synchronous commands in batches
    • createAsyncCommands: task for creating asynchronous commands in batches

    targets

    No

    Device ID array, which is the target for executing the batch task.

    document

    No

    Task execution data file, in JSON format (key-value pairs). For details, see Deliver a Command to a Device.

  2. The platform returns a 201 Created message to the application.
  3. The device receives the command and sends the command result to the platform through the upstream topic. For details, see Platform Delivering a Command.
  4. Call the API for querying the batch task list to query the execution status of a batch command delivery task.

Asynchronous Command Delivery

Asynchronous command delivery is used for IoTDA or applications to deliver commands to devices using LwM2M over CoAP to access IoTDA. Two modes are available.

Table 4 Asynchronous command delivery

Type

Description

Scenario

Process

Immediate delivery of asynchronous commands

IoTDA delivers commands to a device upon receiving a command regardless of whether the device is online. If the device is offline or the device does not receive the command, the delivery fails.

It is used in scenarios that have high requirements for timeliness.

Immediate Delivery of Asynchronous Commands

Delayed delivery of asynchronous commands

The platform caches a command and delivers it to a device when the device goes online or reports properties. If a device has multiple cached commands, the platform delivers the commands in sequence.

Delayed delivery applies to commands that do not need to be executed immediately, for example, configuring water meter parameters.

Delayed Delivery of Asynchronous Commands

Immediate Delivery of Asynchronous Commands

Figure 2 Command delivery for devices using LwM2M over CoAP

An example of the corresponding steps is as follows:

  1. An application calls the API for delivering an asynchronous command to send a command to the platform. The send_strategy parameter in the command request is set to immediately. Example message:
    POST https://{endpoint}/v5/iot/{project_id}/devices/{device_id}/async-commands
    Content-Type: application/json
    X-Auth-Token: ********
    
    {
      "service_id" : "WaterMeter",
      "command_name" : "ON_OFF",
      "paras" : {
        "value" : "ON"
      },
       "expire_time": 0,
       "send_strategy": "immediately"
    }
  2. The platform uses the codec to encode the command request, and sends the command through the Execute operation of the device management and service implementation interface defined in the LwM2M protocol. The message body is in binary format.
  3. The platform sends a 200 OK message carrying the command status SENT to the application. (If the device is offline or the device does not receive the command, the delivery fails and the command status is FAILED.)
  4. The device returns an ACK message after receiving the command.
  5. If the application has subscribed to command status change notifications, the platform pushes a message to the application by calling the API for pushing a command status change notification. The command status carried in the message is DELIVERED. Example message:
    Method: POST
    request:
    Body:
    {
        "resource": "device.command.status",
        "event": "update",
        "event_time": "20200811T080745Z",
        "notify_data": {
            "header": {
                "app_id": "********",
                "device_id": "********",
                "node_id": "test0001",
                "product_id": "********",
                "gateway_id": "********",
                "tags": []
            },
            "body": {
                "command_id": "********",
                "created_time": "20200811T080738Z",
                "sent_time": "20200811T080738Z",
                "delivered_time": "20200811T080745Z",
                "response_time": "",
                "status": "DELIVERED",
                "result": null
            }
        }
    }
  6. After the command is executed, the device returns the command execution result in a 205 Content message.
  7. If the application has subscribed to command status change notifications, the platform uses the codec to decode the command response and sends a push message to the application by calling the API for pushing a command status change notification. The command status carried in the message is SUCCESSFUL. Example message:
    Method: POST
    request:
    Body:
    {
        "resource": "device.command.status",
        "event": "update",
        "event_time": "20200811T080745Z",
        "notify_data": {
            "header": {
                "app_id": "********",
                "device_id": "********",
                "node_id": "test0001",
                "product_id": "********",
                "gateway_id": "********",
                "tags": []
            },
            "body": {
                "command_id": "********",
                "created_time": "20200811T080738Z",
                "sent_time": "20200811T080738Z",
                "delivered_time": "20200811T080745Z",
                "response_time": "20200811T081745Z",
                "status": "SUCCESSFUL",
                "result": {
                    "resultCode":"SUCCESSFUL",
                    "resultDetail": {
                        "value": "ON"
                    }
                }
            }
        }
    }

Delayed Delivery of Asynchronous Commands

Figure 3 Delayed command delivery for devices using LwM2M over CoAP
  1. An application calls the API for delivering an asynchronous command to send a command to the platform. The send_strategy parameter in the command request is set to delay.
  2. The platform adds the command to the cache queue and reports a 200 OK message. The command status is PENDING.
  3. The device goes online or reports data to the platform.
  4. The platform uses the codec to encode the command request and sends the command to the device according to the protocol specifications.
  5. If the application has subscribed to command status change notifications, the platform pushes a message to the application by calling the API for pushing a command status change notification. The command status carried in the message is SENT.
  6. The subsequent flow is the same as 4 to 7 described in the immediate delivery scenario.

LwM2M/CoAP Device Command Execution Status

The figure below illustrates the command execution status and the table below describes the status change mechanism.

Figure 4 LwM2M/CoAP command delivery status
Table 5 LwM2M/CoAP command execution status

Status

Description

PENDING

  • For a device using LwM2M over CoAP in delayed delivery mode, the platform caches a command if the device has not reported data. The command status is PENDING.
  • This status does not exist for devices using LwM2M over CoAP in immediate delivery mode.

EXPIRED

  • For a device using LwM2M over CoAP in delayed delivery mode, if the platform does not deliver a command to the device within a specified time, the command status is EXPIRED. The expiration time is subject to the value of expireTime carried in the command request. If expireTime is not carried, the default value (24 hours) is used.
  • This status does not exist for devices using LwM2M over CoAP in immediate delivery mode.

SENT

  • For a device using LwM2M over CoAP in delayed delivery mode, the platform sends a cached command when receiving data reported by the device. In this case, the command status changes from PENDING to SENT.
  • For a device using LwM2M over CoAP in immediate delivery mode, if the device is online when the platform delivers a command, the command status is SENT.

TIMEOUT

If the platform does not receive a response within 180 seconds after delivering a command to a device using LwM2M over CoAP, the command status is TIMEOUT.

DELIVERED

If the platform receives a response from a device, the command status is DELIVERED.

SUCCESSFUL

If the platform receives a result indicating that the command is executed, the command status is SUCCESSFUL.

FAILED

  • If the platform receives a result indicating that the command execution failed, the command status is FAILED.
  • For a device using LwM2M over CoAP in immediate delivery mode, if the device is offline when the platform delivers a command, the command status is FAILED.

Platform Command Delivery Example

  1. Access the IoTDA service page and click Access Console. Click the target instance card.
  2. In the navigation pane, choose Devices > All Devices. On the device list, click a device to access its details page.
  3. The Cloud Delivery tab page varies according to the device protocol.

    • Devices using MQTT support only synchronous command delivery. Click Command Delivery on the right. In the displayed dialog box, select the command to be delivered and set command parameters.
      Figure 5 Command delivery - Synchronous command delivery
    • Devices using LwM2M over CoAP support only asynchronous command delivery. Click Deliver Command on the right. In the displayed dialog box, select the command to be delivered and set command parameters. You can choose to send the command immediately or after a delay.
      Figure 6 Command delivery - Asynchronous command delivery

  • On the Message Trace tab page, you can view the creation time, sending time, delivered time, and the delivery status of a command delivery task. This information helps you learn the command execution status.
  • In addition, you can call the API for querying a command with a specific ID to query the status and content of delivered commands on the platform.

The application uses the Java SDK for the development of synchronous command delivery. The development environment used in the example is JDK 1.8 or later. Download an SDK.

  1. Configure the Maven dependency.

    <dependency>
        <groupId>com.huaweicloud.sdk</groupId>
        <artifactId>huaweicloud-sdk-core</artifactId>
        <version>[3.0.40-rc, 3.2.0)</version>
    </dependency>
    <dependency>
        <groupId>com.huaweicloud.sdk</groupId>
        <artifactId>huaweicloud-sdk-iotda</artifactId>
        <version>[3.0.40-rc, 3.2.0)</version>
    </dependency>

  2. The following is an example of delivering a synchronous command:

    public class CommandSolution {
        // REGION_ID: If CN East-Shanghai1 is used, enter cn-east-3. If CN North-Beijing4 is used, enter cn-north-4. If CN South-Guangzhou is used, enter cn-south-4.
        private static final String REGION_ID = "<YOUR REGION ID>";
        // ENDPOINT: On the console, choose Overview and click Access Addresses to view the HTTPS application access address.
        private static final String ENDPOINT = "<YOUR ENDPOINT>";
        // For the standard or enterprise edition, create a region object.
        public static final Region REGION_CN_NORTH_4 = new Region(REGION_ID, ENDPOINT);
        public static void main(String[] args) {
            String ak = "<YOUR AK>";
            String sk = "<YOUR SK>";
            String projectId = "<YOUR PROJECTID>";
            // Create a credential.
            ICredential auth = new BasicCredentials().withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE)
                .withAk(ak)
                .withSk(sk)
                .withProjectId(projectId);
            // Create and initialize an IoTDAClient instance.
            IoTDAClient client = IoTDAClient.newBuilder().withCredential(auth)
                // For the basic edition, select the region object in IoTDARegion.
                //.withRegion(IoTDARegion.CN_NORTH_4)
                // For the standard or enterprise edition, create a region object.
                .withRegion(REGION_CN_NORTH_4).build();
            // Instantiate a request object.
            CreateCommandRequest request = new CreateCommandRequest();
            request.withDeviceId("<YOUR DEVICE_ID>");
            DeviceCommandRequest body = new DeviceCommandRequest();
            body.withParas("{\"value\":\"1\"}");
            request.withBody(body);
            try {
                CreateCommandResponse response = client.createCommand(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    Table 6 Parameters

    Parameter

    Description

    ak

    Access key ID (AK) of your Huawei Cloud account. You can create and check your AK/SK on the My Credentials > Access Keys page of the Huawei Cloud console. For details, see Access Keys.

    sk

    Secret access key (SK) of your Huawei Cloud account.

    projectId

    Project ID. For details on how to obtain a project ID, see Obtaining a Project ID.

    IoTDARegion.CN_NORTH_4

    Region where the platform to be accessed is located. The available regions of the platform have been defined in the SDK code IoTDARegion.java.

    On the console, you can view the region name of the current service and the mapping between regions and endpoints. For details, see Platform Connection Information.

    REGION_ID

    If CN East-Shanghai1 is used, enter cn-east-3. If CN North-Beijing4 is used, enter cn-north-4. If CN South-Guangzhou is used, enter cn-south-4.

    ENDPOINT

    On the console, choose Overview and click Access Addresses to view the HTTPS application access address.

    DEVICE_ID

    Unique ID of the device that a message is delivered to. The value of this parameter is allocated by the platform during device registration. The value is a string of no more than 128 characters. Only letters, digits, underscores (_), and hyphens (-) are allowed.

To configure the device to use the Java SDK to deliver synchronous commands, perform the following steps. In this example, JDK 1.8 or a later version is used.

  1. 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>

  2. 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.
    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 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;
    }

  3. Set the command delivery callback function and send a response.

     client.setCommandListener(new CommandListener() {
        @Override
        public void onCommand(String requestId, String serviceId, String commandName, Map<String, Object> paras) {
            log.info("onCommand, serviceId = " +serviceId);
            log.info("onCommand , name = " + commandName);
            log.info("onCommand, paras =  " + paras.toString());
    
            // Define the processing command.
    
            // Send a command response.
            device.getClient().respondCommand(requestId, new CommandRsp(0));
        }   
    });

Verify the setting:

  1. On the IoTDA console, click the target instance card. In the navigation pane, choose Devices > All Devices. On the displayed page, locate the target device, and click View in the Operation column to access its details page. Click the Message Trace tab, and click Start Trace.

    Figure 7 Message tracing - Starting message tracing

  2. Run the SDK code on the device to bring the device online.
  3. Run the application code. After receiving a command, the device processes and responds to the command. The following is an example of a command received by the device.

    Figure 8 Successful command delivery result on the device

  4. Check the result on the Message Trace tab page.

    Figure 9 Message tracing - Delivering commands