

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 開始和監控命令執行
<a name="iot-remote-command-execution-start-monitor"></a>

建立命令後，在目標裝置上啟動執行。裝置會更新結果並將狀態發佈至 MQTT 預留主題。從您的帳戶擷取和監控執行狀態。

使用 AWS IoT 主控台或 啟動和監控命令 AWS CLI。

**Topics**
+ [啟動命令執行](#iot-remote-command-execution-start)
+ [更新命令執行的結果](#iot-remote-command-execution-update)
+ [擷取命令執行](#iot-remote-command-execution-get)
+ [使用 MQTT 測試用戶端檢視命令更新](#iot-remote-command-execution-update-mqtt)
+ [在 中列出命令執行 AWS 帳戶](#iot-remote-command-execution-list)
+ [刪除命令執行](#iot-remote-command-execution-delete)

## 啟動命令執行
<a name="iot-remote-command-execution-start"></a>

**重要**  
您全權負責以安全且符合相關法律的方式部署命令。

開始執行之前，請確定：
+ 您已在具有承載資訊的 AWS IoT 命名空間中建立 命令。開始執行時，裝置會處理承載指示並執行指定的動作。如需建立命令[建立命令資源](iot-remote-command-create-manage.md#iot-remote-command-create)的詳細資訊，請參閱 。
+ 您的裝置已訂閱 命令的 MQTT 預留主題。開始執行時，承載資訊會發佈至此預留 MQTT 請求主題：

  *<devices>* 可以是 Things 或 MQTT 用戶端。*<DeviceID>* 是物件名稱或用戶端 ID。支援的 *<PayloadFormat>* 值：JSON 和 CBOR。如需詳細資訊，請參閱[命令主題](reserved-topics.md#reserved-topics-commands)。

  ```
  $aws/commands/<devices>/<DeviceID>/executions/+/request/<PayloadFormat>
  ```

  對於非 JSON/CBOR *<PayloadFormat>*，請使用下列命令主題格式：

  ```
  $aws/commands/<devices>/<DeviceID>/executions/+/request
  ```

### 目標裝置考量事項
<a name="iot-command-execution-target"></a>

指定要接收和執行 命令的目標裝置。將物件名稱用於已註冊的裝置，或將用戶端 ID 用於未註冊的裝置。收到承載後，裝置會執行 命令並執行指定的動作。

#### AWS IoT 物件
<a name="iot-command-execution-target-thing"></a>

目標裝置可以是在 AWS IoT 登錄檔中註冊的物件。物件可簡化裝置搜尋和管理。

從 [Connect 裝置頁面或使用 將裝置](https://console.aws.amazon.com/iot/home#/connect-overview)註冊為實物[https://docs.aws.amazon.com/iot/latest/apireference/API_CreateThing.html](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateThing.html)。從[物件中樞](https://console.aws.amazon.com/iot/home#/thinghub)或使用 尋找現有的物件[https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeThing.html](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeThing.html)。如需註冊詳細資訊[，請參閱使用登錄檔管理物件](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry)。

#### 用戶端 ID
<a name="iot-command-execution-target-clientid"></a>

對於未註冊的裝置，請使用用戶端 ID。

用戶端 ID 是您指派給裝置的唯一識別符。在 MQTT 通訊協定中定義，其中包含英數字元、底線或破折號。連線至 的每個裝置 AWS IoT 都需要唯一的用戶端 ID。

**注意**  
對於已註冊的物件，用戶端 ID 可以符合物件名稱。
以特定用戶端 ID 為目標時，裝置必須使用 AWS IoT 該用戶端 ID 連線至 ，才能接收承載。

用戶端 ID 是連線至 時使用的 MQTT 用戶端 ID 裝置 AWS IoT Core。 AWS IoT 使用此 ID 來識別裝置和管理連線和訂閱。

### 命令執行逾時考量
<a name="iot-command-execution-timeout"></a>

逾時會指定裝置提供執行結果的持續時間 （以秒為單位）。

建立執行後，計時器會啟動。如果裝置離線或無法在逾時內報告結果，則執行會逾時，狀態為 `TIMED_OUT`。

預設：10 秒。上限：12 小時。

#### 逾時值和`TIMED_OUT`執行狀態
<a name="iot-command-execution-timeout-status"></a>

雲端和裝置都可以報告逾時。

傳送 命令後，計時器會啟動。如果沒有裝置回應在逾時內到達，則雲端會將執行狀態設定為 ，`TIMED_OUT`原因碼為 `$NO_RESPONSE_FROM_DEVICE`。

發生下列情況時，會發生這種情況：
+ 裝置在執行期間離線。
+ 裝置無法在逾時內完成執行。
+ 裝置無法在逾時內報告狀態。

在此執行個體中，當從雲端報告 `TIMED_OUT`的執行狀態時，命令執行是非終端的。您的裝置可以發佈回應，將狀態覆寫為任何終端狀態：`FAILED`、 `SUCCEEDED`或 `REJECTED`。然後，命令執行會變成終端機，且不接受任何進一步的更新。

您的裝置也可以透過報告執行命令時發生逾時，來更新雲端啟動`TIMED_OUT`的狀態。在此情況下，命令執行狀態會保持在 `TIMED_OUT`，但會根據裝置報告的資訊更新`statusReason`物件。命令執行接著會變成終端機，而且不接受進一步的更新。

#### 使用 MQTT 持久性工作階段
<a name="iot-command-execution-timeout-persistent"></a>

您可以設定 MQTT 持久性工作階段，以搭配 AWS IoT Device Management 命令功能使用。此功能在裝置離線且您希望確保裝置在逾時持續時間之前恢復上線時仍能收到命令，並執行指定的指示等情況下特別有用。

MQTT 持續性工作階段到期時間預設為 60 分鐘。如果您的命令執行逾時設定為超過此持續時間的值，執行時間超過 60 分鐘的命令執行可能會被訊息代理程式拒絕並失敗。若要執行持續期間超過 60 分鐘的命令，您可以請求增加持續性工作階段到期時間。

**注意**  
為了確保您正確使用 MQTT 持久性工作階段功能，請將 Clean Start 旗標設為零。如需詳細資訊，請參閱 [MQTT 持續性工作階段](https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html#mqtt-persistent-sessions)。

### 啟動命令執行 （主控台）
<a name="iot-remote-command-execution-start-console"></a>

若要從主控台開始執行命令，請前往 AWS IoT 主控台的 [Command Hub](https://console.aws.amazon.com/iot/home#/commandHub) 頁面並執行下列步驟。

1. 若要執行您已建立的命令，請選擇**執行命令**。

1. 檢閱您所建立命令的相關資訊，包括 MQTT 預留主題和參數，如適用。

   針對動態命令，輸入參數值或保留預設值。對於沒有預設值的參數，您必須提供要作為此執行的一部分傳送的值。

1. 指定要接收和執行 命令的目標裝置。如果裝置已向 註冊，則可以將其指定為 AWS IoT 物件 AWS IoT，如果裝置尚未註冊，則可以使用用戶端 ID。如需詳細資訊，請參閱[目標裝置考量事項](#iot-command-execution-target)

1. （選用） 設定命令的逾時值，決定您希望命令在逾時之前執行的持續時間。如果您的命令需要執行超過 60 分鐘，您可能需要增加 MQTT 持久性工作階段到期時間。如需詳細資訊，請參閱[命令執行逾時考量](#iot-command-execution-timeout)。

1. 選擇**執行命令**。

### 啟動命令執行 (AWS CLI)
<a name="iot-remote-command-execution-start-cli"></a>

使用 [https://docs.aws.amazon.com/iot/latest/apireference/API_StartCommandExecution.html](https://docs.aws.amazon.com/iot/latest/apireference/API_StartCommandExecution.html) HTTP 資料平面 API 操作來啟動命令執行。API 請求和回應與命令執行 ID 相關聯。裝置完成執行命令後，可以透過將訊息發佈至命令回應主題，向雲端報告狀態和執行結果。對於自訂回應碼，您擁有的應用程式碼可以處理回應訊息並將結果發佈到其中 AWS IoT。

如果您的裝置已訂閱命令請求主題，`StartCommandExecution`API 會將承載訊息發佈至主題。承載可以使用您選擇的任何格式。如需詳細資訊，請參閱[命令承載](iot-remote-command-create-manage.md#iot-commands-payload)。

```
$aws/commands/<devices>/<DeviceID>/executions/+/request/<PayloadFormat>
```

如果承載格式不是 JSON 或 CBOR，則以下顯示命令請求主題的格式。

```
$aws/commands/<devices>/<DeviceID>/executions/+/request
```

#### 範例 IAM 政策
<a name="iot-remote-command-execution-start-policy"></a>

使用此 API 操作之前，請確定您的 IAM 政策授權您在裝置上執行此動作。下列範例顯示 IAM 政策，允許使用者執行 `StartCommandExecution`動作的許可。

在此範例中，取代：
+ `region` ， AWS 區域例如 `us-east-1`。
+ `account-id` 您的 AWS 帳戶 號碼，例如 `123456789012`。
+ `command-id` 具有 AWS IoT 命令的唯一識別符，例如 `LockDoor`。如果您想要傳送多個命令，您可以在 IAM 政策中指定這些命令。
+ `devices` 使用 `thing`或 ，`client`取決於您的裝置是否已註冊為 AWS IoT 實物，或指定為 MQTT 用戶端。
+ `device-id` 您的 AWS IoT `thing-name`或 `client-id`。

```
{
  "Effect": "Allow",
  "Action": [
      "iot:StartCommandExecution"
  ],
  "Resource": [
      "arn:aws:iot:region:account-id:command/command-id",
      "arn:aws:iot:region:account-id:devices/device-id"
  ]
}
```

若要查看 支援的條件金鑰清單`StartCommandExecution`，請參閱《*IAM 使用者指南*》中的 [的條件金鑰 AWS IoT](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-policy-keys)。

#### 取得帳戶特定的資料平面端點
<a name="iot-remote-command-execution-start-endpoint"></a>

執行 API 命令之前，您必須取得端點的帳戶特定端點 URL。如果您使用的是雙堆疊端點 (IPv4 和 IPv6)，請使用 `iot:Data-ATS`。`iot:Jobs` 端點僅適用於 IPv4。例如，如果您執行此命令：

```
aws iot describe-endpoint --endpoint-type iot:Data-ATS
```

它會傳回帳戶特定的端點 URL，如以下範例回應所示。

```
{
    "endpointAddress":
    "<account-specific-prefix>-ats.iot.<region>.api.com"
}
```

#### 啟動命令執行範例 (AWS CLI)
<a name="iot-remote-command-execution-start-example"></a>

下列範例顯示如何使用 命令開始執行`start-command-execution` AWS CLI 命令。

在此範例中，取代：
+ *`<command-arn>`* 搭配您要執行之命令的 ARN。您可以從 CLI `create-command` 命令的回應取得此資訊。例如，如果您正在執行變更方向盤模式的命令，請使用 `arn:aws:iot:region:account-id:command/SetComfortSteeringMode`。
+ *`<target-arn>`* 目標裝置的物件 ARN，可以是您要執行命令的 IoT 物件或 MQTT 用戶端。例如，如果您要執行目標裝置 的 命令`myRegisteredThing`，請使用 `arn:aws:iot:region:account-id:thing/myRegisteredThing`。
+ *`<endpoint-url>`* 使用您在 中取得的帳戶特定端點[取得帳戶特定的資料平面端點](#iot-remote-command-execution-start-endpoint)，字首為 `https://`。例如 `https://123456789012abcd.jobs.iot.us-east-1.amazonaws.com`。
+ （選用） 您也可以在執行 `StartCommandExecution` API 操作時指定其他參數 `executionTimeoutSeconds`。此選用欄位指定裝置必須完成執行命令的時間，以秒為單位。根據預設，值為 10 秒。當命令執行狀態為 時`CREATED`，計時器會啟動。如果在計時器過期之前未收到命令執行結果，則狀態會自動變更為 `TIMED_OUT`。
+ 

  ```
  aws iot-jobs-data start-command-execution \
      --command-arn <command-arn>  \
      --target-arn <target-arn> \  
      --endpoint <endpoint-url> \ 
      --execution-timeout-seconds 900
  ```
+ （選用） 對於動態命令，指定要用於替換的參數及其值。您必須為在命令建立時未設定 defaultValue 的參數提供值。如果參數具有 defaultValue，則此處提供的參數值優先。對於設定 valueConditions 的參數，此處提供的參數值必須符合條件。

  根據`Light_Power_Status`動態命令範例：
+ 

  ```
  aws iot-jobs-data start-command-execution \
      --command-arn arn:aws:iot:us-east-1:123456789012:command/Light_Power_Status  \
      --target-arn arn:aws:iot:us-east-1:123456789012:thing/exampleThing \
      --endpoint <endpoint-url> \
      --execution-timeout-seconds 900 \
      --parameters "powerStatus={S=ON}"
  ```

執行此命令會傳回命令執行 ID。您可以使用此 ID 來查詢命令執行狀態、詳細資訊和命令執行歷史記錄。

**注意**  
如果命令已棄用，則 `StartCommandExecution` API 請求會失敗並出現驗證例外狀況。若要修正此錯誤，請先使用 `UpdateCommand` API 還原命令，然後執行`StartCommandExecution`請求。

```
{
    "executionId": "07e4b780-7eca-4ffd-b772-b76358da5542"
}
```

## 更新命令執行的結果
<a name="iot-remote-command-execution-update"></a>

使用 `UpdateCommandExecution` MQTT 資料平面 API 操作來更新命令執行的狀態或結果。

**注意**  
使用此 API 之前：  
您的裝置必須已建立 MQTT 連線並訂閱命令請求和回應主題。如需詳細資訊，請參閱[高階命令工作流程](iot-remote-command-workflow.md)。
您必須已使用 `StartCommandExecution` API 操作執行此命令。

### 範例 IAM 政策
<a name="iot-remote-command-execution-update-policy"></a>

使用此 API 操作之前，請確定您的 IAM 政策授權您的裝置執行這些動作。以下顯示範例政策，授權您的裝置執行 動作。如需允許使用者執行 `UpdateCommandExecution` MQTT 動作之許可的其他範例 IAM 政策，請參閱 [連線和發佈政策範例](connect-and-pub.md)。

在此範例中，取代：
+ `Region` ， AWS 區域例如 `us-east-1`。
+ `AccountID` 使用您的 AWS 帳戶 號碼，例如 *`123456789012`*。
+ `ThingName` 您以命令執行為目標的 AWS IoT 物件名稱，例如 *`myRegisteredThing`*。
+ `commands-request-topic` 和 `commands-response-topic` 以及您 AWS IoT 命令請求和回應主題的名稱。如需詳細資訊，請參閱[高階命令工作流程](iot-remote-command-workflow.md)。

#### MQTT 用戶端 ID 的 IAM 政策範例
<a name="iot-remote-command-execution-update-policy-client"></a>

下列程式碼顯示使用 MQTT 用戶端 ID 時的範例裝置政策。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:Publish",
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/response",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/response/json"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "iot:Receive",
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/request",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/response/accepted",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/response/rejected",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/request/json",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/response/accepted/json",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/clients/${iot:ClientId}/executions/*/response/rejected/json"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "iot:Subscribe",
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/clients/${iot:ClientId}/executions/+/request",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/clients/${iot:ClientId}/executions/+/response/accepted",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/clients/${iot:ClientId}/executions/+/response/rejected",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/clients/${iot:ClientId}/executions/+/request/json",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/clients/${iot:ClientId}/executions/+/response/accepted/json",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/clients/${iot:ClientId}/executions/+/response/rejected/json"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "iot:Connect",
      "Resource": "arn:aws:iot:us-east-1:123456789012:client/${iot:ClientId}"
    }
  ]
}
```

#### IoT 物件的 IAM 政策範例
<a name="iot-remote-command-execution-update-policy-thing"></a>

下列程式碼顯示使用 AWS IoT 物件時的範例裝置政策。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:Publish",
      "Resource": "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/response"
    },
    {
      "Effect": "Allow",
      "Action": "iot:Receive",
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/request",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/response/accepted",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/response/rejected",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/request/json",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/response/accepted/json",
        "arn:aws:iot:us-east-1:123456789012:topic/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/*/response/rejected/json"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "iot:Subscribe",
      "Resource": [
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/+/request",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/+/response/accepted",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/+/response/rejected",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/+/request/json",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/+/response/accepted/json",
        "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/commands/things/${iot:Connection.Thing.ThingName}/executions/+/response/rejected/json"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "iot:Connect",
      "Resource": "arn:aws:iot:us-east-1:123456789012:client/${iot:ClientId}"
    }
  ]
}
```

### 如何使用 `UpdateCommandExecution` API
<a name="iot-remote-command-execution-update-works"></a>

在請求主題收到命令執行後，裝置會處理命令。然後，它會使用 `UpdateCommandExecution` API 將命令執行的狀態和結果更新為下列回應主題。

```
$aws/commands/<devices>/<DeviceID>/executions/<ExecutionId>/response/<PayloadFormat>
```

在此範例中， *`<DeviceID>`*是目標裝置的唯一識別符，而 *`<execution-id>`*是目標裝置上命令執行的識別符。*<PayloadFormat>* 可以是 JSON 或 CBOR。

**注意**  
如果您尚未向 註冊裝置 AWS IoT，您可以使用用戶端 ID 做為識別符，而不是物件名稱。

```
$aws/commands/clients/<ClientID>/executions/<ExecutionId>/response/<PayloadFormat>
```

#### 裝置回報執行狀態的更新
<a name="iot-command-execution-reported"></a>

您的裝置可以使用 API 向命令執行報告下列任何狀態更新。如需這些狀態的詳細資訊，請參閱 [命令執行狀態](iot-remote-command-concepts.md#iot-command-execution-status)。
+ `IN_PROGRESS`：當裝置開始執行命令時，它可以將狀態更新為 `IN_PROGRESS`。
+ `SUCCEEDED`：當裝置成功處理命令並完成執行時，裝置可以將訊息發佈至回應主題，做為 `SUCCEEDED`。
+ `FAILED`：如果裝置無法執行 命令，它可以將訊息發佈至回應主題，做為 `FAILED`。
+ `REJECTED`：如果裝置無法接受 命令，它可以將訊息發佈至回應主題，做為 `REJECTED`。
+ `TIMED_OUT`：`TIMED_OUT`由於下列任何原因，命令執行狀態可能會變更為 。
  + 未收到命令執行的結果。這可能是因為未在指定的持續時間內完成執行，或裝置無法將狀態資訊發佈至回應主題。
  + 裝置報告嘗試執行 命令時發生逾時。

如需 `TIMED_OUT` 狀態的詳細資訊，請參閱 [逾時值和`TIMED_OUT`執行狀態](#iot-command-execution-timeout-status)。

#### 使用 `UpdateCommandExecution` API 時的考量事項
<a name="iot-remote-command-execution-update-considerations"></a>

以下是使用 `UpdateCommandExecution` API 時的一些重要考量。
+ 您的裝置可以使用選用`statusReason`物件來提供有關執行的其他資訊。如果您的裝置提供此物件，則需要 物件`reasonCode`的欄位，但 `reasonDescription` 欄位是選用的。
+ 當您的裝置使用 `statusReason` 物件時， `reasonCode` 必須使用 模式`[A-Z0-9_-]+`，長度不得超過 64 個字元。如果您提供 `reasonDescription`，請確保長度不超過 1，024 個字元。它可以使用任何字元，但控制字元除外，例如換行。
+ 您的裝置可以使用選用`result`物件來提供命令執行結果的相關資訊，例如遠端函數呼叫的傳回值。如果您提供 `result`，它必須至少需要一個項目。
+ 在 `result` 欄位中，您將項目指定為鍵/值對。對於每個項目，您必須將資料類型資訊指定為字串、布林值或二進位。字串資料類型必須使用金鑰 `s`，布林值資料類型必須使用金鑰 `b`，而二進位資料類型必須使用金鑰 `bin`。請確定這些金鑰為小寫。
+ 如果您在執行 `UpdateCommandExecution` API 時發生錯誤，您可以在 Amazon CloudWatch 的`AWSIoTLogsV2`日誌群組中檢視錯誤。如需啟用記錄和檢視日誌的資訊，請參閱 [設定 AWS IoT 記錄](configure-logging.md)。

#### `UpdateCommandExecution` API 範例
<a name="iot-remote-command-execution-update-example"></a>

以下程式碼顯示您的裝置如何使用 `UpdateCommandExecution` API 報告執行狀態的範例、提供狀態額外資訊`statusReason`的欄位，以及提供執行結果相關資訊的結果欄位，例如在此情況下的汽車電池百分比。

```
{
  "status": "IN_PROGRESS",
  "statusReason": {
    "reasonCode": "200",
    "reasonDescription": "Execution_in_progress"
  },
  "result": {
        "car_battery": {
            "s": "car battery at 50 percent"
        }
    }
}
```

## 擷取命令執行
<a name="iot-remote-command-execution-get"></a>

執行命令後，您可以從 AWS IoT 主控台和使用 擷取命令執行的相關資訊 AWS CLI。您可以取得下列資訊。

**注意**  
若要擷取最新的命令執行狀態，您的裝置必須使用 `UpdateCommandExecution` MQTT API 將狀態資訊發佈至回應主題，如下所述。在裝置發佈至此主題之前，`GetCommandExecution`API 會將狀態報告為 `CREATED`或 `TIMED_OUT`。

您建立的每個命令執行作業都會有：
+ **執行 ID**，這是命令執行作業的唯一識別碼。
+ 命令執行的**狀態**。當您在目標裝置上執行命令時，命令執行作業會進入 `CREATED` 狀態。然後作業會轉換成其他命令執行狀態，如下所述。
+ 命令執行**的結果**。
+ 唯一的**命令 ID** 和已建立執行作業的目標裝置。
+ **開始日期**，顯示命令執行作業建立的時間。

### 擷取命令執行 （主控台）
<a name="iot-remote-command-execution-get-console"></a>

您可以使用下列其中一種方法，從主控台擷取命令執行。
+ 

**從命令中樞頁面**  
前往 AWS IoT 主控台的 [Command Hub](https://console.aws.amazon.com/iot/home#/commandHub) 頁面，並執行這些步驟。

  1. 選擇您在目標裝置上建立執行的命令。

  1. 在命令詳細資訊頁面的**命令歷史記錄**索引標籤中，您會看到您建立的執行。選擇您要擷取資訊的執行。

  1. 如果您的裝置使用 `UpdateCommandExecution` API 提供結果資訊，您可以在此頁面**的結果**索引標籤中找到此資訊。
+ 

**從物件中樞頁面**  
如果您在執行 命令時選擇 AWS IoT 物件做為目標裝置，您可以從物件中樞頁面檢視執行詳細資訊。

  1. 前往 AWS IoT 主控台中的[物件中樞](https://console.aws.amazon.com/iot/home#/thinghub)頁面，然後選擇您為其建立命令執行的物件。

  1. 在物件詳細資訊頁面的**命令歷史記錄**中，您會看到您建立的執行。選擇您要擷取資訊的執行。

  1. 如果您的裝置使用 `UpdateCommandExecution` API 提供結果資訊，您可以在此頁面**的結果**索引標籤中找到此資訊。

### 擷取命令執行 (CLI)
<a name="iot-remote-command-execution-get-cli"></a>

使用[https://docs.aws.amazon.com/iot/latest/apireference/API_GetCommandExecution.html](https://docs.aws.amazon.com/iot/latest/apireference/API_GetCommandExecution.html) AWS IoT Core 控制平面 HTTP API 操作來擷取命令執行的相關資訊。您必須已使用 `StartCommandExecution` API 操作執行此命令。

#### 範例 IAM 政策
<a name="iot-remote-command-execution-get-policy"></a>

使用此 API 操作之前，請確定您的 IAM 政策授權您在裝置上執行此動作。下列範例顯示 IAM 政策，允許使用者執行 `GetCommandExecution`動作的許可。

在此範例中，取代：
+ `region` ， AWS 區域例如 `us-east-1`。
+ `account-id` 您的 AWS 帳戶 號碼，例如 `123456789012`。
+ `command-id` 您的唯一 AWS IoT 命令識別符，例如 `LockDoor`。
+ `devices` 使用 `thing`或 ，`client`取決於您的裝置是否已註冊為 AWS IoT 實物，或指定為 MQTT 用戶端。
+ `device-id` 您的 AWS IoT `thing-name`或 `client-id`。

```
{
  "Effect": "Allow",
  "Action": [
      "iot:GetCommandExecution"
  ],
  "Resource": [
      "arn:aws:iot:region:account-id:command/command-id",
      "arn:aws:iot:region:account-id:devices/device-id"
  ]
}
```

#### 擷取命令執行範例
<a name="iot-remote-command-execution-get-example"></a>

下列範例說明如何擷取使用 命令執行之`start-command-execution` AWS CLI 命令的相關資訊。下列範例顯示如何擷取已執行之命令的相關資訊，以關閉方向盤模式。

在此範例中，取代：
+ *`<execution-id>`* 具有您要擷取資訊的命令執行識別符。
+ *`<target-arn>`* 您以執行為目標之裝置的 Amazon Resource Number (ARN)。您可以從 CLI `start-command-execution` 命令的回應取得此資訊。
+ 或者，如果您的裝置使用 `UpdateCommandExection` API 提供執行結果，您可以指定是否使用 `GetCommandExecution` API 在 `GetCommandExecution` API 回應中包含命令執行結果。

```
aws iot get-command-execution  
    --execution-id <execution-id> \ 
    --target-arn <target-arn> \
    --include-result
```

執行此命令會產生回應，其中包含命令執行的 ARN、執行狀態，以及開始執行的時間，以及完成時間的相關資訊。它也提供 `statusReason` 物件，其中包含 狀態的其他資訊。如需不同狀態和狀態原因的詳細資訊，請參閱 [命令執行狀態](iot-remote-command-concepts.md#iot-command-execution-status)。

下列程式碼顯示來自 API 請求的範例回應。

**注意**  
執行回應中的 `completedAt` 欄位對應至裝置向雲端回報終端機狀態的時間。在`TIMED_OUT`狀態的情況下，只有在裝置報告逾時時，才會設定此欄位。狀態由雲端設定`TIMED_OUT`時，`TIMED_OUT`狀態不會更新。如需逾時行為的詳細資訊，請參閱 [命令執行逾時考量](#iot-command-execution-timeout)。

```
{
    "executionId": "07e4b780-7eca-4ffd-b772-b76358da5542",
    "commandArn": "arn:aws:iot:us-east-1:123456789012:command/LockDoor",
    "targetArn": "arn:aws:iot:us-east-1:123456789012:thing/myRegisteredThing",
    "status": "SUCCEEDED",
    "statusReason": {
        "reasonCode": "DEVICE_SUCCESSFULLY_EXECUTED",
        "reasonDescription": "SUCCESS"
    },
    "result": {
        "sn": { "s": "ABC-001" },
        "digital": { "b": true }        
    },
    "createdAt": "2024-03-23T00:50:10.095000-07:00",
    "completedAt": "2024-03-23T00:50:10.095000-07:00"    
}
```

## 使用 MQTT 測試用戶端檢視命令更新
<a name="iot-remote-command-execution-update-mqtt"></a>

使用命令功能時，您可以使用 MQTT 測試用戶端透過 MQTT 檢視訊息交換。在您的裝置與 建立 MQTT 連線後 AWS IoT，您可以建立命令、指定承載，然後在裝置上執行它。當您執行 命令時，如果您的裝置訂閱命令的 MQTT 預留請求主題，它會看到發佈至此主題的承載訊息。

然後，裝置會收到承載指示，並在 AWS IoT 裝置上執行指定的操作。然後，它會使用 `UpdateCommandExecution` API 將命令執行結果和狀態資訊發佈至 command. AWS IoT Device Management listens 的 MQTT 預留回應主題，以更新回應主題並儲存更新的資訊，並將日誌發佈至 AWS CloudTrail 和 Amazon CloudWatch。然後，您可以從主控台或使用 `GetCommandExecution` API 擷取最新的命令執行資訊。

下列步驟說明如何使用 MQTT 測試用戶端來觀察訊息。

1. 在 AWS IoT 主控台中開啟 [MQTT 測試用戶端](https://console.aws.amazon.com/iot/home#/test)。

1. 在**訂閱**索引標籤上，輸入下列主題，然後選擇**訂閱**，其中 *<thingId>* 是您已註冊之裝置的物件名稱 AWS IoT。
**注意**  
您可以從 AWS IoT 主控台的物件[中樞](https://console.aws.amazon.com/iot/home#/thinghub)頁面找到裝置的物件名稱。如果您尚未將裝置註冊為物件，您可以在 AWS IoT 從 [Connect 裝置頁面連線至 時註冊裝置](https://console.aws.amazon.com/iot/home#/connect-overview)。

   ```
   $aws/commands/things/<thingId>/executions/+/request
   ```

1. （選用） 在**訂閱**索引標籤上，您也可以輸入下列主題，然後選擇**訂閱**。

   ```
   $aws/commands/things/+/executions/+/response/accepted/json
   $aws/commands/things/+/executions/+/response/rejected/json
   ```

1. 當您啟動命令執行時，將使用裝置已訂閱的請求主題 ，將訊息承載傳送至裝置`$aws/commands/things/<thingId>/executions/+/request`。在 MQTT 測試用戶端中，您應該會看到命令承載，其中包含裝置處理命令的指示。

1. 裝置開始執行命令後，可以發佈狀態更新至下列命令的 MQTT 預留回應主題。

   ```
   $aws/commands/<devices>/<device-id>/executions/<executionId>/response/json
   ```

   例如，請考慮您執行的命令，以開啟汽車的 AC，將溫度降至所需的值。下列 JSON 顯示 車輛發佈至回應主題的範例訊息，顯示無法執行 命令。

   ```
   {
     "deviceId": "My_Car",
     "executionId": "07e4b780-7eca-4ffd-b772-b76358da5542",
     "status": "FAILED",
     "statusReason": {
       "reasonCode": "CAR_LOW_ON_BATTERY",
       "reasonDescription": "Car battery is lower than 5 percent"
     }
   }
   ```

   在這種情況下，您可以為汽車的電池充電，然後再次執行 命令。

## 在 中列出命令執行 AWS 帳戶
<a name="iot-remote-command-execution-list"></a>

執行命令之後，您可以從 AWS IoT 主控台和使用 擷取命令執行的相關資訊 AWS CLI。您可以取得下列資訊。
+ **執行 ID**，這是命令執行作業的唯一識別碼。
+ 命令執行的**狀態**。當您在目標裝置上執行命令時，命令執行作業會進入 `CREATED` 狀態。然後作業會轉換成其他命令執行狀態，如下所述。
+ 唯一的**命令 ID** 和已建立執行作業的目標裝置。
+ **開始日期**，顯示命令執行作業建立的時間。

### 列出您帳戶中的命令執行 （主控台）
<a name="iot-remote-command-execution-list-console"></a>

您可以使用下列其中一種方法，從主控台查看所有命令執行。
+ 

**從命令中樞頁面**  
前往 AWS IoT 主控台的 [Command Hub](https://console.aws.amazon.com/iot/home#/commandHub) 頁面，並執行這些步驟。

  1. 選擇您在目標裝置上建立執行的命令。

  1. 在命令詳細資訊頁面中，前往**命令歷史記錄**索引標籤，您會看到您建立的執行清單。
+ 

**從物件中樞頁面**  
如果您在執行 命令時選擇 AWS IoT 物件做為目標裝置，並為單一裝置建立多個命令執行，您可以從物件中樞頁面檢視裝置的執行。

  1. 前往 AWS IoT 主控台中的[物件中樞](https://console.aws.amazon.com/iot/home#/thinghub)頁面，然後選擇您為其建立執行的物件。

  1. 在物件詳細資訊頁面的**命令歷史記錄**中，您會看到為裝置建立的執行清單。

### 列出您帳戶中的命令執行 (CLI)
<a name="iot-remote-command-execution-list-cli"></a>

使用[https://docs.aws.amazon.com/iot/latest/apireference/API_ListCommandExecutions.html](https://docs.aws.amazon.com/iot/latest/apireference/API_ListCommandExecutions.html) AWS IoT Core 控制平面 HTTP API 操作列出您帳戶中的所有命令執行。

#### 範例 IAM 政策
<a name="iot-remote-command-execution-list-policy"></a>

使用此 API 操作之前，請確定您的 IAM 政策授權您在裝置上執行此動作。下列範例顯示 IAM 政策，允許使用者執行 `ListCommandExecutions`動作的許可。

在此範例中，取代：
+ `region` ， AWS 區域例如 `us-east-1`。
+ `account-id` 使用您的 AWS 帳戶 號碼，例如 `123456789012`。
+ `command-id` 您的唯一 AWS IoT 命令識別符，例如 `LockDoor`。

```
{
  "Effect": "Allow",
  "Action": "iot:ListCommandExecutions",
  "Resource": *
}
```

#### 列出命令執行範例
<a name="iot-remote-command-execution-list-example"></a>

下列範例示範如何在 中列出命令執行 AWS 帳戶。

執行 命令時，您必須指定是否要篩選清單，以僅顯示使用 為特定裝置建立的命令執行`targetArn`，還是使用 為特定命令指定的執行`commandArn`。

在此範例中，取代：
+ *`<target-arn>`* 您以執行為目標之裝置的 Amazon Resource Number (ARN)，例如 `arn:aws:iot:us-east-1:123456789012:thing/b8e4157c98f332cffb37627f`。
+ *`<target-arn>`* 您以執行為目標之裝置的 Amazon Resource Number (ARN)，例如 `arn:aws:iot:us-east-1:123456789012:thing/b8e4157c98f332cffb37627f`。
+ *`<after>`* 以及您想要列出建立之執行的時間，例如 `2024-11-01T03:00`。

```
aws iot list-command-executions \ 
--target-arn <target-arn> \ 
--started-time-filter '{after=<after>}' \
--sort-order "ASCENDING"
```

執行此命令會產生回應，其中包含您建立的命令執行清單、執行開始執行的時間，以及執行完成的時間。它也提供狀態資訊，以及包含狀態額外資訊的`statusReason`物件。

```
{
    "commandExecutions": [
        {
            "commandArn": "arn:aws:iot:us-east-1:123456789012:command/TestMe002",
            "executionId": "b2b654ca-1a71-427f-9669-e74ae9d92d24",
            "targetArn": "arn:aws:iot:us-east-1:123456789012:thing/b8e4157c98f332cffb37627f",
            "status": "TIMED_OUT",
            "createdAt": "2024-11-24T14:39:25.791000-08:00",
            "startedAt": "2024-11-24T14:39:25.791000-08:00"
        },
        {
            "commandArn": "arn:aws:iot:us-east-1:123456789012:command/TestMe002",
            "executionId": "34bf015f-ef0f-4453-acd0-9cca2d42a48f",
            "targetArn": "arn:aws:iot:us-east-1:123456789012:thing/b8e4157c98f332cffb37627f",
            "status": "IN_PROGRESS",
            "createdAt": "2024-11-24T14:05:36.021000-08:00",
            "startedAt": "2024-11-24T14:05:36.021000-08:00"
        }
    ]
}
```

如需不同狀態和狀態原因的詳細資訊，請參閱 [命令執行狀態](iot-remote-command-concepts.md#iot-command-execution-status)。

## 刪除命令執行
<a name="iot-remote-command-execution-delete"></a>

如果您不想再使用命令執行，可以從您的帳戶永久移除它。

**注意**  
命令執行只有在進入終端狀態時才能刪除，例如 `SUCCEEDED`、 `FAILED`或 `REJECTED`。
此操作只能使用 AWS IoT Core API 或 執行 AWS CLI。它無法從 主控台使用。

### 範例 IAM 政策
<a name="iot-remote-command-execution-delete-policy"></a>

使用此 API 操作之前，請確定您的 IAM 政策授權您的裝置執行這些動作。以下顯示範例政策，授權您的裝置執行 動作。

在此範例中，取代：
+ `Region` 您的 AWS 區域，例如 `us-east-1`。
+ `AccountID` 使用您的 AWS 帳戶 號碼，例如 *`123456789012`*。
+ `CommandID` 具有您要刪除執行之命令的識別符。
+ `devices` 使用 `thing`或 ，`client`取決於您的裝置是否已註冊為 AWS IoT 實物，或指定為 MQTT 用戶端。
+ `device-id` 您的 AWS IoT `thing-name`或 `client-id`。

```
{
  "Effect": "Allow",
  "Action": [
      "iot:DeleteCommandExecution"
  ],
  "Resource": [
      "arn:aws:iot:region:account-id:command/command-id",
      "arn:aws:iot:region:account-id:devices/device-id"
  ]
}
```

### 刪除命令執行範例
<a name="iot-remote-command-execution-delete-example"></a>

下列範例示範如何使用 命令刪除`delete-command` AWS CLI 命令。根據您的應用程式，將 *`<execution-id>`*取代為您要刪除之命令執行的識別符，並將 *`<target-arn>`*取代為您目標裝置的 ARN。

```
aws iot delete-command-execution \ 
--execution-id <execution-id> \ 
--target-arn <target-arn>
```

如果 API 請求成功，則命令執行會產生 200 狀態碼。您可以使用 `GetCommandExecution` API 來驗證 帳戶中不再存在命令執行。