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.
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.
|
|
Applicable |
Not applicable |
For details, see Synchronous Command Delivery and Asynchronous Command Delivery.
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.
APIs
- APIs for the platform and applications
- APIs for MQTT devices
- APIs for devices using LwM2M over CoAP
Synchronous Command Delivery
You can deliver synchronous commands to MQTT devices one by one or in batches.
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 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 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.
- 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" } }
- 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" } }
- 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" } }
- 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.
- 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.
- The platform returns a 201 Created message to the application.
- The device receives the command and sends the command result to the platform through the upstream topic. For details, see Platform Delivering a Command.
- 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.
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. |
|
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. |
Immediate Delivery of Asynchronous Commands
An example of the corresponding steps is as follows:
- 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" }
- 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.
- 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.)
- The device returns an ACK message after receiving the command.
- 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 } } }
- After the command is executed, the device returns the command execution result in a 205 Content message.
- 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
- 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.
- The platform adds the command to the cache queue and reports a 200 OK message. The command status is PENDING.
- The device goes online or reports data to the platform.
- The platform uses the codec to encode the command request and sends the command to the device according to the protocol specifications.
- 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.
- 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.
Status |
Description |
---|---|
PENDING |
|
EXPIRED |
|
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 |
|
Platform Command Delivery Example
- Access the IoTDA service page and click Access Console. Click the target instance card.
- In the navigation pane, choose Devices > All Devices. On the device list, click a device to access its details page.
- 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
- 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.
- 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.
- 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>
- 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.
- 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>
- 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; }
- 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:
- 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
- Run the SDK code on the device to bring the device online.
- 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
- Check the result on the Message Trace tab page.
Figure 9 Message tracing - Delivering commands
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot