

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

# AWS IoT SiteWise 從 AWS IoT 實物擷取資料至
<a name="ingest-data-from-iot-things"></a>

在本教學課程中，了解如何使用裝置陰影 AWS IoT SiteWise ，從 AWS IoT 實物機群將資料擷取至 。*裝置陰影*是存放 AWS IoT 裝置目前狀態資訊的 JSON 物件。如需詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的[裝置陰影服務](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html)。

完成本教學課程後，您可以 AWS IoT SiteWise 根據 AWS IoT 實物在 中設定 操作。透過使用 AWS IoT 實物，您可以將操作與 的其他實用功能整合 AWS IoT。例如，您可以設定 AWS IoT 功能來執行下列任務：
+ 設定其他規則，將資料串流至 [AWS IoT Events](https://docs.aws.amazon.com/iotevents/latest/developerguide/)、[Amazon DynamoDB](https://docs.aws.amazon.com/dynamodb/) 和其他 AWS 服務。如需詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的[規則](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html)。
+ 使用 AWS IoT 機群索引服務索引、搜尋和彙總您的裝置資料。如需詳細資訊，請參閱[《 開發人員指南》中的機群索引服務](https://docs.aws.amazon.com/iot/latest/developerguide/iot-indexing.html)。 *AWS IoT *
+ 使用 稽核並保護您的裝置 AWS IoT Device Defender。如需詳細資訊，請參閱《AWS IoT 開發人員指南》**中的 [AWS IoT Device Defender](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/what-is-device-defender.html)。

在本教學課程中，您將了解如何將資料從 AWS IoT 物件的裝置影子擷取至資產 AWS IoT SiteWise。若要這樣做，您可以建立一或多個 AWS IoT 物件，並執行指令碼，使用 CPU 和記憶體用量資料更新每個物件的裝置影子。您會使用本教學課程中的 CPU 和記憶體用量資料來模擬實際感應器資料。然後，您建立具有 AWS IoT SiteWise 動作的規則，此動作 AWS IoT SiteWise 會在每次物件的裝置影子更新時將此資料傳送至資產。如需詳細資訊，請參閱[AWS IoT SiteWise 使用 AWS IoT Core 規則將資料擷取至](iot-rules.md)。

**Topics**
+ [先決條件](#rule-ingestion-tutorial-prerequisites)
+ [步驟 1：建立 AWS IoT 政策](#ingestion-tutorial-create-iot-policy)
+ [步驟 2：建立和設定 AWS IoT 物件](#rule-tutorial-create-iot-thing)
+ [步驟 3：建立裝置資產模型](#rule-tutorial-create-device-model)
+ [步驟 4：建立裝置機群資產模型](#rule-tutorial-create-fleet-model)
+ [步驟 5：建立和設定裝置資產](#rule-tutorial-create-device-assets)
+ [步驟 6：建立和設定裝置機群資產](#rule-tutorial-create-fleet-asset)
+ [步驟 7：在 AWS IoT Core 中建立規則，以將資料傳送至裝置資產](#rule-tutorial-create-iot-rule)
+ [步驟 8：執行裝置用戶端指令碼](#rule-tutorial-run-script)
+ [步驟 9：在教學課程後清除資源](#rule-tutorial-clean-up-resources)

## 先決條件
<a name="rule-ingestion-tutorial-prerequisites"></a>

為了完成本教學，您需要以下項目：
+  AWS 帳戶。如果您沒有帳戶，請參閱 [設定 AWS 帳戶](getting-started.md#set-up-aws-account)。
+ 執行 Windows、Linux、 macOS或 Unix以存取 的開發電腦 AWS 管理主控台。如需詳細資訊，請參閱 [AWS 管理主控台入門](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/getting-started.html)。
+ 具有管理員許可的 AWS Identity and Access Management (IAM) 使用者。
+ Python 3 安裝在開發電腦上，或安裝在您要註冊為 AWS IoT 物件的裝置上。

## 步驟 1：建立 AWS IoT 政策
<a name="ingestion-tutorial-create-iot-policy"></a>

在此程序中，建立 AWS IoT 政策，允許 AWS IoT 物件存取本教學課程中使用的資源。

------
#### [ Console ]

使用下列程序來使用 AWS IoT Core 主控台建立 AWS IoT 政策：

**建立 AWS IoT 政策**

1. 登入 [AWS 管理主控台](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/what-is.html)。

1. 檢閱 AWS IoT SiteWise 支援的 [AWS 區域](https://docs.aws.amazon.com/general/latest/gr/iot-sitewise.html)。視需要切換到其中一個支援的區域。

1. 導覽至 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。如果出現 **Connect 裝置**按鈕，請選擇它。

1. 在左側導覽窗格中，選擇**安全性**，然後選擇**政策**。

1. 選擇**建立**。

1. 輸入 AWS IoT 政策的名稱 （例如 **SiteWiseTutorialDevicePolicy**)。

1. 在**政策文件**下，選擇 **JSON** 以 JSON 格式輸入下列政策。將 *region* 和 *account-id* 取代為您的區域和帳戶 ID，例如 **us-east-1** 和 **123456789012**。

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": "iot:Connect",
         "Resource": "arn:aws:iot:us-east-1:123456789012:client/SiteWiseTutorialDevice*"
       },
       {
         "Effect": "Allow",
         "Action": "iot:Publish",
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get"
         ]
       },
       {
         "Effect": "Allow",
         "Action": "iot:Receive",
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/accepted",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/accepted",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/accepted",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/rejected",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/rejected"
         ]
       },
       {
         "Effect": "Allow",
         "Action": "iot:Subscribe",
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/accepted",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/accepted",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/accepted",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/rejected",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/rejected"
         ]
       },
       {
         "Effect": "Allow",
         "Action": [
           "iot:GetThingShadow",
           "iot:UpdateThingShadow",
           "iot:DeleteThingShadow"
         ],
         "Resource": "arn:aws:iot:us-east-1:123456789012:thing/SiteWiseTutorialDevice*"
   
       }
     ]
   }
   ```

------

1. 選擇**建立**。

------
#### [ AWS CLI ]

**重要**  
此政策使用萬用字元來保持在 CLI AWS IoT SiteWise 大小限制內。如需具有明確主題路徑的更嚴格許可，請改為透過 AWS IoT SiteWise 主控台建立政策。如需詳細資訊，請參閱 標籤上提供的 IoT 政策範例。

使用下列 AWS CLI 命令來建立 IoT 政策：

```
aws iot create-policy \
  --policy-name "SiteWiseTutorialDevicePolicy" \
  --policy-document '{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": "iot:Connect",
        "Resource": "arn:aws:iot:region:account-id:client/SiteWiseTutorialDevice*"
      },
      {
        "Effect": "Allow",
        "Action": ["iot:Publish", "iot:Receive"],
        "Resource": [
          "arn:aws:iot:region:account-id:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": "iot:Subscribe",
        "Resource": [
          "arn:aws:iot:region:account-id:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "iot:GetThingShadow",
          "iot:UpdateThingShadow",
          "iot:DeleteThingShadow"
        ],
        "Resource": "arn:aws:iot:region:account-id:thing/SiteWiseTutorialDevice*"
      }
    ]
  }'
```

若要確認您的政策已成功建立，請使用下列命令：

```
aws iot get-policy --policy-name "SiteWiseTutorialDevicePolicy"
```

------

此政策可讓 AWS IoT 裝置建立連線，並使用 MQTT 訊息與裝置陰影通訊。如需 MQTT 訊息的詳細資訊，請參閱[什麼是 MQTT？](https://aws.amazon.com/what-is/mqtt/)。若要與裝置影子互動，您的 AWS IoT 物件會在開頭為 的主題上發佈和接收 MQTT 訊息`$aws/things/thing-name/shadow/`。此政策包含稱為 的物件政策變數`${iot:Connection.Thing.ThingName}`。此變數會取代每個主題中連線的物件名稱。`iot:Connect` 陳述式會設定哪些裝置可以建立連線的限制，確保物件政策變數只能取代以 開頭的名稱`SiteWiseTutorialDevice`。

如需詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的[物件政策變數](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policy-variables.html)。

**注意**  
此政策適用於名稱開頭為 `SiteWiseTutorialDevice` 的實物。若要使用不同的實物名稱，您必須據此更新政策。

## 步驟 2：建立和設定 AWS IoT 物件
<a name="rule-tutorial-create-iot-thing"></a>

在此程序中，您會建立和設定 AWS IoT 物件。您可以將開發電腦指定為 AWS IoT 物件。隨著您的進度，請記住，您在這裡學習的原則可以套用至實際專案。您可以靈活地在任何能夠執行 AWS IoT SDK 的裝置上建立和設定 AWS IoT 物件，包括 AWS IoT Greengrass 和 FreeRTOS。如需詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的 [AWS IoT SDKs](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html)。

------
#### [ Console ]

**建立和設定 AWS IoT 物件**

1. 開啟命令列並執行下列命令，為本教學課程建立目錄。

   ```
   mkdir iot-sitewise-rule-tutorial
   cd iot-sitewise-rule-tutorial
   ```

1. 執行下列命令，為實物的憑證建立目錄。

   ```
   mkdir device1
   ```

   如果您正在建立其他實物，請據此在目錄名稱中使用遞增的編號，以追蹤哪些憑證屬於哪些實物。

1. 導覽至 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格中，選擇**管理**區段中的所有**裝置**。然後選擇 **Things (實物)**。

1. 如果出現 **You don't have any things yet (您尚未有任何實物)** 對話方塊，請選擇 **Create a thing (建立實物)**。否則，請選擇**建立物件**。

1. 在**建立物件**頁面上，選擇**建立單一物件**，然後選擇**下一步**。

1. 在**指定物件屬性**頁面上，輸入 AWS IoT 物件的名稱 （例如，**SiteWiseTutorialDevice1**)，然後選擇**下一步**。如果您正在建立其他實物，請據此在實物名稱中使用遞增的編號。
**重要**  
物件名稱必須符合您在*步驟 1：建立政策中建立 AWS IoT *的政策中使用的名稱。否則，您的裝置無法連線到 AWS IoT。

1. 在**設定裝置憑證 - *選用***頁面上，選擇**自動產生新憑證 （建議）**，然後選擇**下一步**。憑證 AWS IoT 可讓 安全地識別您的裝置。

1. 在**將政策連接至憑證 - *選用***頁面上，選取您在*步驟 1：建立 AWS IoT 政策中建立的政策，*然後選擇**建立物件**。

1. 在**下載憑證和金鑰**對話方塊中，執行下列動作：

   1. 選擇 **Download (下載)** 連結，以下載實物的憑證、公有金鑰和私有金鑰。將這三個檔案全部儲存到您為實物憑證建立的目錄 (例如 **iot-sitewise-rule-tutorial/device1**)。
**重要**  
只有此時能夠下載實物的憑證和金鑰，裝置需要這些資訊才能成功連線到 AWS IoT。

   1. 選擇**下載**連結以下載根 CA 憑證。將根憑證授權機構憑證儲存至 **iot-sitewise-rule-tutorial**。建議您下載 Amazon 根憑證授權機構 1。

1. 選擇**完成**。

------
#### [ AWS CLI ]

請依照下列步驟，使用 建立和設定 AWS IoT 物件 AWS CLI：

1. 開啟命令列並執行下列命令來建立本教學課程的目錄：

   ```
   mkdir iot-sitewise-rule-tutorial
   ```

1. 導覽至教學課程目錄：

   ```
   cd iot-sitewise-rule-tutorial
   ```

1. 執行下列命令，為物件的憑證建立目錄：

   ```
   mkdir device1
   ```

   如果您正在建立其他實物，請據此在目錄名稱中使用遞增的編號，以追蹤哪些憑證屬於哪些實物。

1. 建立 AWS IoT 物件：

   ```
   aws iot create-thing --thing-name "SiteWiseTutorialDevice1"
   ```
**重要**  
物件名稱必須符合您在步驟 1 中建立的政策中使用的名稱模式。否則，您的裝置無法連線到 AWS IoT。

1. 建立憑證並儲存檔案。請注意來自輸出的憑證 ARN - 您將在後續步驟中使用它：

   ```
   aws iot create-keys-and-certificate \
       --set-as-active \
       --certificate-pem-outfile "device1/device.pem.crt" \
       --public-key-outfile "device1/public.pem.key" \
       --private-key-outfile "device1/private.pem.key"
   ```

1. 將您在步驟 1 中建立的政策連接到憑證：

   ```
   aws iot attach-policy \
       --policy-name "SiteWiseTutorialDevicePolicy" \
       --target "certificate-arn"
   ```

1. 將憑證連接至物件：

   ```
   aws iot attach-thing-principal \
       --thing-name "SiteWiseTutorialDevice1" \
       --principal "certificate-arn"
   ```

1. 下載 Amazon 根 CA 憑證：

   ```
   curl https://www.amazontrust.com/repository/AmazonRootCA1.pem > AmazonRootCA1.pem
   ```

   您的裝置需要此憑證才能成功連線至 AWS IoT。

**重要**  
安全地存放您的憑證和金鑰。您無法在建立這些登入資料之後再次下載這些登入資料。

------

您現在已在電腦上註冊 AWS IoT 實物。採取下列其中一個後續步驟：
+ 繼續*步驟 3：建立裝置資產模型*而不建立其他 AWS IoT 物件。您可以只使用一個實物完成本教學課程。
+ 在另一部電腦或裝置上重複本節的步驟，以建立更多 AWS IoT 實物。針對本教學課程，建議您按照此選項進行，這樣就能從多個裝置擷取唯一的 CPU 和 記憶體用量資料。
+ 在同一部裝置 (您的電腦) 上重複本節的步驟，以建立更多 AWS IoT 實物。每個 AWS IoT 物件都會從您的電腦接收類似的 CPU 和記憶體用量資料，因此請使用此方法示範從多個裝置擷取非唯一的資料。

## 步驟 3：建立裝置資產模型
<a name="rule-tutorial-create-device-model"></a>

在此程序中，您會在 中建立資產模型 AWS IoT SiteWise ，以代表串流 CPU 和記憶體用量資料的裝置。若要處理代表裝置群組的資產中的資料，資產模型會跨相同類型的多個資產強制執行一致的資訊。如需詳細資訊，請參閱[模型工業資產](industrial-asset-models.md)。

**建立代表裝置的資產模型**

1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)。

1. 在左側導覽窗格中選擇 **Models (模型)**。

1. 選擇**建立資產模型**。

1. 在**模型詳細資訊**下，輸入模型的名稱。例如 **SiteWise Tutorial Device Model**。

1. 在 **Measurement definitions (衡量值定義)** 底下，執行下列操作：

   1. 在**名稱**中，輸入 **CPU Usage**。

   1. 在 **Unit (單位)** 中輸入 **%**。

   1. 將 **Data type (資料類型)** 保留為 **Double (雙倍)**。

   衡量值屬性代表裝置的原始資料串流。如需詳細資訊，請參閱[從設備定義資料串流 （度量）](measurements.md)。

1. 選擇**新增測量**以新增第二個測量屬性。

1. 在 **Measurement definitions (衡量值定義)** 底下的第二列中，執行下列操作：

   1. 在**名稱**中，輸入 **Memory Usage**。

   1. 在 **Unit (單位)** 中輸入 **%**。

   1. 將 **Data type (資料類型)** 保留為 **Double (雙倍)**。

1. 在 **Metric definitions (指標定義)** 底下，執行下列操作：

   1. 在**名稱**中，輸入 **Average CPU Usage**。

   1. 在 **Formula (公式)** 中輸入 **avg(CPU Usage)**。自動完成清單中出現 **CPU Usage** 時，請選擇此選項。

   1. 在 **Time interval (時間間隔)** 中輸入 **5 minutes**。

   指標屬性會定義彙總計算，處理某個間隔的所有輸入資料點，並在每個間隔輸出單一資料點。此指標屬性會每隔 5 分鐘計算一次每部裝置的平均 CPU 用量。如需詳細資訊，請參閱[從屬性和其他資產彙總資料 （指標）](metrics.md)。

1. 選擇**新增指標**以新增第二個指標屬性。

1. 在 **Metric definitions (指標定義)** 底下的第二列中，執行下列操作：

   1. 在**名稱**中，輸入 **Average Memory Usage**。

   1. 在 **Formula (公式)** 中輸入 **avg(Memory Usage)**。自動完成清單中出現 **Memory Usage** 時，請選擇此選項。

   1. 在 **Time interval (時間間隔)** 中輸入 **5 minutes**。

   此指標屬性會每隔 5 分鐘計算一次每部裝置的平均記憶體用量。

1. (選用) 新增您想對每部裝置計算的其他指標。有一些有趣的函數，包括 `min` 和 `max`。如需詳細資訊，請參閱[使用公式表達式](formula-expressions.md)。在*步驟 4：建立裝置機群資產模型*中，您可以建立父系資產，以使用來自整個裝置機群的資料來計算指標。

1. 選擇**建立模型**。

## 步驟 4：建立裝置機群資產模型
<a name="rule-tutorial-create-fleet-model"></a>

在此程序中，您會在 中製作資產模型 AWS IoT SiteWise ，以表示裝置集合的符號。在此資產模型中，您建立的結構可讓您將許多裝置資產連結至一個整體機群資產。接下來，您會在機群資產模型中概述指標，以合併來自所有連線裝置資產的資料。此方法可讓您全面了解整個機群的集體效能。

**建立代表裝置機群的資產模型**

1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)。

1. 在左側導覽窗格中選擇 **Models (模型)**。

1. 選擇**建立資產模型**。

1. 在**模型詳細資訊**下，輸入模型的名稱。例如 **SiteWise Tutorial Device Fleet Model**。

1. 在 **Hierarchy definitions (階層定義)** 底下，執行下列操作：

   1. 在 **Hierarchy name (階層名稱)** 中輸入 **Device**。

   1. 在 **Hierarchy model (階層模型)** 中，選擇裝置資產模型 (**SiteWise Tutorial Device Model**)。

   階層會定義父系 (機群) 資產模型與子系 (裝置) 資產模型之間的關係。父系資產可存取子系資產的屬性資料。當您稍後建立資產時，您必須根據父系資產模型中的階層定義，建立子系資產與父系資產的關聯。如需詳細資訊，請參閱[資產階層代表設備關係](industrial-asset-models.md#asset-hierarchies)。

1. 在 **Metric definitions (指標定義)** 底下，執行下列操作：

   1. 在**名稱**中，輸入 **Average CPU Usage**。

   1. 在 **Formula (公式)** 中輸入 **avg(Device \$1 Average CPU Usage)**。自動完成清單出現時，請選擇 **Device** 以選擇階層，然後選擇 **Average CPU Usage** 以從您先前建立的裝置資產中選擇指標。

   1. 在 **Time interval (時間間隔)** 中輸入 **5 minutes**。

   此指標屬性會透過 **Device** 階層，計算與機群資產相關聯之所有裝置資產的平均 CPU 用量。

1. 選擇**新增指標**以新增第二個指標屬性。

1. 在 **Metric definitions (指標定義)** 底下的第二列中，執行下列操作：

   1. 在**名稱**中，輸入 **Average Memory Usage**。

   1. 在 **Formula (公式)** 中輸入 **avg(Device \$1 Average Memory Usage)**。自動完成清單出現時，請選擇 **Device** 以選擇階層，然後選擇 **Average Memory Usage** 以從您先前建立的裝置資產中選擇指標。

   1. 在 **Time interval (時間間隔)** 中輸入 **5 minutes**。

   此指標屬性會透過 **Device** 階層，計算與機群資產相關聯之所有裝置資產的平均記憶體用量。

1. (選用) 新增您想在裝置機群中計算的其他指標。

1. 選擇**建立模型**。

## 步驟 5：建立和設定裝置資產
<a name="rule-tutorial-create-device-assets"></a>

在此程序中，您會根據裝置資產模型產生裝置資產。接著，您會定義每個衡量值屬性的屬性別名。*屬性別名*是可識別資產屬性的唯一字串。稍後，您可以使用別名來識別資料上傳的屬性，而不是資產 ID 和屬性 ID。如需詳細資訊，請參閱[管理 的資料串流 AWS IoT SiteWise](manage-data-streams.md)。

**建立裝置資產和定義屬性別名**

1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)。

1. 在左側導覽窗格中，選擇 **Assets (資產)**。

1. 選擇 **Create asset (建立資產)**。

1. 在**模型資訊**下，選擇您的裝置資產模型 **SiteWise Tutorial Device Model**。

1. 在**資產資訊**下，輸入資產的名稱。例如 **SiteWise Tutorial Device 1**。

1. 選擇 **Create asset (建立資產)**。

1. 針對新裝置資產，選擇 **Edit (編輯)**。

1. 在**測量**下：

   1. 在 **CPU Usage** 底下，輸入 **/tutorial/device/SiteWiseTutorialDevice1/cpu** 做為屬性別名。您可以在 屬性別名中包含 AWS IoT 物件的名稱，以便使用單一 AWS IoT 規則從所有裝置擷取資料。

   1. 在 **Memory Usage** 底下，輸入 **/tutorial/device/SiteWiseTutorialDevice1/memory** 做為屬性別名。

1. 選擇**儲存**。

如果您先前已建立多個 AWS IoT 物件，請為每個裝置重複步驟 3 到 10，並相應地增加資產名稱和屬性別名中的數字。例如，第二個裝置資產的名稱應為 **SiteWise Tutorial Device 2**，而其屬性別名應為 **/tutorial/device/SiteWiseTutorialDevice2/cpu** 及 **/tutorial/device/SiteWiseTutorialDevice2/memory**。

## 步驟 6：建立和設定裝置機群資產
<a name="rule-tutorial-create-fleet-asset"></a>

在此程序中，您會形成衍生自裝置機群資產模型的裝置機群資產。然後，您將個別裝置資產連結至機群資產。此關聯可讓機群資產的指標屬性編譯和分析來自多個裝置的資料。此資料為您提供整個機群集體效能的合併檢視。

**建立裝置機群資產並與裝置資產建立關聯**

1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)。

1. 在左側導覽窗格中，選擇 **Assets (資產)**。

1. 選擇 **Create asset (建立資產)**。

1. 在**模型資訊**下，選擇您的裝置機群資產模型 **SiteWise Tutorial Device Fleet Model**。

1. 在**資產資訊**下，輸入資產的名稱。例如 **SiteWise Tutorial Device Fleet 1**。

1. 選擇 **Create asset (建立資產)**。

1. 針對新裝置機群資產，選擇 **Edit (編輯)**。

1. 在**與此資產相關聯的資產**下，選擇**新增相關聯的資產**並執行下列動作：

   1. 在 **Hierarchy (階層)** 底下，選擇 **Device**。此階層會識別裝置和裝置機群資產之間的階層關係。您先前已按照本教學課程在裝置機群資產模型中定義此階層。

   1. 在 **Asset (資產)** 底下，選擇裝置資產 **SiteWise Tutorial Device 1**。

1. （選用） 如果您先前已建立多個裝置資產，請為您建立的每個裝置資產重複步驟 8 到 10。

1. 選擇**儲存**。

   您現在應該會看到裝置資產整理為階層的形式。

## 步驟 7：在 AWS IoT Core 中建立規則，以將資料傳送至裝置資產
<a name="rule-tutorial-create-iot-rule"></a>

在此程序中，您會在 中建立規則 AWS IoT Core。此規則旨在解譯來自裝置陰影的通知訊息，並將資料傳輸到 中的裝置資產 AWS IoT SiteWise。每次您裝置的陰影更新時， 都會 AWS IoT 傳送 MQTT 訊息。您可建立規則，根據 MQTT 訊息在裝置陰影變更時執行動作。在此情況下，目標是處理更新訊息、擷取屬性值，並將其傳輸至您的裝置資產 AWS IoT SiteWise。

**使用 AWS IoT SiteWise 動作建立規則**

1. 導覽至 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格中，選擇**訊息路由**，然後選擇**規則**。

1. 選擇**建立規則**。

1. 輸入規則的名稱和描述，然後選擇**下一步**。

1. 輸入下列 SQL 陳述式，然後選擇**下一步**。

   ```
   SELECT
     *
   FROM
     '$aws/things/+/shadow/update/accepted'
   WHERE
     startsWith(topic(3), "SiteWiseTutorialDevice")
   ```

   此規則查詢陳述式能夠運作的原因在於，裝置陰影服務會將陰影更新發佈到 `$aws/things/thingName/shadow/update/accepted`。如需裝置影子的詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的[裝置影子服務](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html)。

   在 `WHERE` 子句中，此規則查詢陳述式使用 `topic(3)` 函數，從本主題的第三個區段中取得實物名稱。接著，陳述式會篩選掉那些具有不符合教學課程裝置之名稱的裝置。如需 AWS IoT SQL 的詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的 [AWS IoT SQL 參考](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-reference.html)。

1. 在**規則動作**下，選擇**將訊息資料傳送至 中的資產屬性 AWS IoT SiteWise**，然後執行下列動作：

   1. 選擇 **By property alias (依據屬性別名)**。

   1. 在 **Property alias (屬性別名)** 中輸入 **/tutorial/device/\$1\$1topic(3)\$1/cpu**。

      `${...}` 語法是替代範本。 會 AWS IoT 評估括號中的內容。此替代範本會從主題中提取實物名稱，建立每個實物的唯一別名。如需詳細資訊，請參閱《 *AWS IoT 開發人員指南*》中的[替代範本](https://docs.aws.amazon.com/iot/latest/developerguide/iot-substitution-templates.html)。
**注意**  <a name="substitution-template-limitations"></a>
因為替代範本中的運算式與 `SELECT` 陳述式是分開計算的，所以您不能使用替代範本來參考使用 `AS` 子句所建立的別名。除了支援的函數與運算子以外，您可以僅參照原始承載中出現的資訊。

   1. 在**項目 ID - *選用***中，輸入 **\$1\$1concat(topic(3), "-cpu-", floor(state.reported.timestamp))\$1**。

      項目 ID 會唯一識別每個值項目的嘗試動作。如果項目傳回錯誤，您可以在錯誤輸出內容中尋找項目 ID，以針對問題進行故障診斷。此項目 ID 中的替代範本會結合實物名稱與裝置回報的時間戳記。例如，產生的項目 ID 看起來可能與 `SiteWiseTutorialDevice1-cpu-1579808494` 類似。

   1. 在 **Time in seconds (以秒為單位的時間)** 中輸入 **\$1\$1floor(state.reported.timestamp)\$1**。

      此替代範本會從裝置回報的時間戳記中計算時間 (以秒為單位)。在本教學課程中，裝置會回報 Unix Epoch 時間格式的時間戳記 (以秒為單位)，做為浮點數。

   1. 在以**奈米為單位的位移 - *選用***，輸入 **\$1\$1floor((state.reported.timestamp % 1) \$1 1E9)\$1**。

      此替代範本會轉換裝置回報的時間戳記的小數部分，藉此從時間中計算奈米秒位移 (以秒為單位)。
**注意**  
AWS IoT SiteWise 需要您的資料具有以 Unix epoch 時間表示的目前時間戳記。如果您的裝置未準確報告時間，您可以從具有 [timestamp()](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-function-timestamp) 的 AWS IoT 規則引擎取得目前的時間。此函數會回報以毫秒為單位的時間，因此您必須將規則動作的時間參數更新為以下的值：  
在 **Time in seconds (以秒為單位的時間)** 中輸入 **\$1\$1floor(timestamp() / 1E3)\$1**。
在 **Offset in nanos (以奈米為單位的位移)** 中輸入 **\$1\$1(timestamp() % 1E3) \$1 1E6\$1**。

   1. 在 **Data type (資料類型)** 中選擇 **Double (雙倍)**。

      此資料類型必須符合您在資產模型中定義之資產屬性的資料類型。

   1. 在 **Value (值)** 中輸入 **\$1\$1state.reported.cpu\$1**。在替代範本中，您會使用 `.` 運算子，以從 JSON 結構內擷取值。

   1. 選擇 **Add entry (新增項目)** 以新增記憶體用量屬性的新項目，然後再次針對該屬性完成下列步驟：

      1. 選擇 **By property alias (依據屬性別名)**。

      1. 在 **Property alias (屬性別名)** 中輸入 **/tutorial/device/\$1\$1topic(3)\$1/memory**。

      1. 在**項目 ID - *選用***中，輸入 **\$1\$1concat(topic(3), "-memory-", floor(state.reported.timestamp))\$1**。

      1. 在 **Time in seconds (以秒為單位的時間)** 中輸入 **\$1\$1floor(state.reported.timestamp)\$1**。

      1. 在以**奈米為單位的位移 - *選用***，輸入 **\$1\$1floor((state.reported.timestamp % 1) \$1 1E9)\$1**。

      1. 在 **Data type (資料類型)** 中選擇 **Double (雙倍)**。

      1. 在 **Value (值)** 中輸入 **\$1\$1state.reported.memory\$1**。

   1. 在 **IAM 角色**下，選擇**建立新角色**，為此規則動作建立 IAM 角色。此角色允許 AWS IoT 將資料推送至裝置機群資產及其資產階層中的屬性。

   1. 輸入角色名稱，然後選擇**建立**。

1. (選用) 設定可用來針對規則進行故障診斷的錯誤動作。如需詳細資訊，請參閱[對規則進行故障診斷 (AWS IoT SiteWise)](troubleshoot-rule.md#rule-tutorial-troubleshoot-rule)。

1. 選擇**下一步**。

1. 檢閱設定，然後選擇**建立**以建立規則。

## 步驟 8：執行裝置用戶端指令碼
<a name="rule-tutorial-run-script"></a>

在本教學課程中，您未使用實際裝置來報告資料。反之，您會執行指令碼，使用 CPU 和記憶體用量來更新 AWS IoT 物件的裝置影子，以模擬真實的感應器資料。若要執行指令碼，您必須先安裝必要的Python套件。在此程序中，您會安裝所需的Python套件，然後執行裝置用戶端指令碼。

**設定和執行裝置用戶端指令碼**

1. 導覽至 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格的底部，選擇 **Settings (設定)**。

1. 儲存自訂端點，以與裝置用戶端指令碼搭配使用。您會使用此端點與實物的陰影進行互動。此端點在您目前區域的帳戶中是唯一的。

   您的自訂端點看起來應該會與以下範例類似。

   ```
   identifier.iot.region.amazonaws.com
   ```

1. 開啟命令列並執行下列命令，以導覽到您先前建立的教學課程目錄。

   ```
   cd iot-sitewise-rule-tutorial
   ```

1. 執行下列命令以安裝 適用於 Python 的 AWS IoT Device SDK。

   ```
   pip3 install AWSIoTPythonSDK
   ```

   如需詳細資訊，請參閱《 *AWS IoT 開發人員指南*[適用於 Python 的 AWS IoT Device SDK](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html#iot-python-sdk)》中的

1. 執行下列命令來安裝 psutil，這是跨平台程序和系統公用程式程式庫。

   ```
   pip3 install psutil
   ```

   如需詳細資訊，請參閱 *Python 套件索引*中的 [psutil](https://pypi.org/project/psutil/)。

1. 在 `iot-sitewise-rule-tutorial` 目錄中建立名為 `thing_performance.py` 的檔案，然後將下列 Python 程式碼複製到檔案中。

   ```
   import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT
   
   import json
   import psutil
   import argparse
   import logging
   import time
   
   
   # Configures the argument parser for this program.
   def configureParser():
       parser = argparse.ArgumentParser()
       parser.add_argument(
           "-e",
           "--endpoint",
           action="store",
           required=True,
           dest="host",
           help="Your AWS IoT custom endpoint",
       )
       parser.add_argument(
           "-r",
           "--rootCA",
           action="store",
           required=True,
           dest="rootCAPath",
           help="Root CA file path",
       )
       parser.add_argument(
           "-c",
           "--cert",
           action="store",
           required=True,
           dest="certificatePath",
           help="Certificate file path",
       )
       parser.add_argument(
           "-k",
           "--key",
           action="store",
           required=True,
           dest="privateKeyPath",
           help="Private key file path",
       )
       parser.add_argument(
           "-p",
           "--port",
           action="store",
           dest="port",
           type=int,
           default=8883,
           help="Port number override",
       )
       parser.add_argument(
           "-n",
           "--thingName",
           action="store",
           required=True,
           dest="thingName",
           help="Targeted thing name",
       )
       parser.add_argument(
           "-d",
           "--requestDelay",
           action="store",
           dest="requestDelay",
           type=float,
           default=1,
           help="Time between requests (in seconds)",
       )
       parser.add_argument(
           "-v",
           "--enableLogging",
           action="store_true",
           dest="enableLogging",
           help="Enable logging for the AWS IoT Device SDK for Python",
       )
       return parser
   
   
   # An MQTT shadow client that uploads device performance data to AWS IoT at a regular interval.
   class PerformanceShadowClient:
       def __init__(
           self,
           thingName,
           host,
           port,
           rootCAPath,
           privateKeyPath,
           certificatePath,
           requestDelay,
       ):
           self.thingName = thingName
           self.host = host
           self.port = port
           self.rootCAPath = rootCAPath
           self.privateKeyPath = privateKeyPath
           self.certificatePath = certificatePath
           self.requestDelay = requestDelay
   
       # Updates this thing's shadow with system performance data at a regular interval.
       def run(self):
           print("Connecting MQTT client for {}...".format(self.thingName))
           mqttClient = self.configureMQTTClient()
           mqttClient.connect()
           print("MQTT client for {} connected".format(self.thingName))
           deviceShadowHandler = mqttClient.createShadowHandlerWithName(
               self.thingName, True
           )
   
           print("Running performance shadow client for {}...\n".format(self.thingName))
           while True:
               performance = self.readPerformance()
               print("[{}]".format(self.thingName))
               print("CPU:\t{}%".format(performance["cpu"]))
               print("Memory:\t{}%\n".format(performance["memory"]))
               payload = {"state": {"reported": performance}}
               deviceShadowHandler.shadowUpdate(
                   json.dumps(payload), self.shadowUpdateCallback, 5
               )
               time.sleep(args.requestDelay)
   
       # Configures the MQTT shadow client for this thing.
       def configureMQTTClient(self):
           mqttClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient(self.thingName)
           mqttClient.configureEndpoint(self.host, self.port)
           mqttClient.configureCredentials(
               self.rootCAPath, self.privateKeyPath, self.certificatePath
           )
           mqttClient.configureAutoReconnectBackoffTime(1, 32, 20)
           mqttClient.configureConnectDisconnectTimeout(10)
           mqttClient.configureMQTTOperationTimeout(5)
           return mqttClient
   
       # Returns the local device's CPU usage, memory usage, and timestamp.
       def readPerformance(self):
           cpu = psutil.cpu_percent()
           memory = psutil.virtual_memory().percent
           timestamp = time.time()
           return {"cpu": cpu, "memory": memory, "timestamp": timestamp}
   
       # Prints the result of a shadow update call.
       def shadowUpdateCallback(self, payload, responseStatus, token):
           print("[{}]".format(self.thingName))
           print("Update request {} {}\n".format(token, responseStatus))
   
   
   # Configures debug logging for the AWS IoT Device SDK for Python.
   def configureLogging():
       logger = logging.getLogger("AWSIoTPythonSDK.core")
       logger.setLevel(logging.DEBUG)
       streamHandler = logging.StreamHandler()
       formatter = logging.Formatter(
           "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
       )
       streamHandler.setFormatter(formatter)
       logger.addHandler(streamHandler)
   
   
   # Runs the performance shadow client with user arguments.
   if __name__ == "__main__":
       parser = configureParser()
       args = parser.parse_args()
       if args.enableLogging:
           configureLogging()
       thingClient = PerformanceShadowClient(
           args.thingName,
           args.host,
           args.port,
           args.rootCAPath,
           args.privateKeyPath,
           args.certificatePath,
           args.requestDelay,
       )
       thingClient.run()
   ```

1. 從命令列搭配下列參數執行 **thing\$1performance.py**：
   + `-n`， `--thingName` – 您的物件名稱，例如 **SiteWiseTutorialDevice1**。
   + `-e`， `--endpoint` – 您在此程序中稍早儲存的自訂 AWS IoT 端點。
   + `-r`， `--rootCA` – AWS IoT 根 CA 憑證的路徑。
   + `-c`， `--cert` – 物件 AWS IoT 憑證的路徑。
   + `-k`， `--key` – 物件 AWS IoT 憑證私有金鑰的路徑。
   + `-d`， `--requestDelay` – （選用） 每次裝置陰影更新之間等待的時間，以秒為單位。預設為 1 秒。
   + `-v`， `--enableLogging` – （選用） 如果此參數存在，指令碼會從 列印偵錯訊息 適用於 Python 的 AWS IoT Device SDK。

   命令看起來應該會與以下範例類似。

   ```
   python3 thing_performance.py \
     --thingName SiteWiseTutorialDevice1 \
     --endpoint identifier.iot.region.amazonaws.com \
     --rootCA AmazonRootCA1.pem \
     --cert device1/thing-id-certificate.pem.crt \
     --key device1/thing-id-private.pem.key
   ```

   如果您正在執行其他 AWS IoT 物件的指令碼，請相應地更新物件名稱和憑證目錄。

1. 嘗試開啟和關閉裝置上的程式，看看 CPU 和記憶體用量有何變化。指令碼會列印每個 CPU 和記憶體用量的讀值。如果指令碼成功將資料上傳到裝置陰影服務，指令碼的輸出看起來應該會與以下範例類似。

   ```
   [SiteWiseTutorialDevice1]
   CPU:    24.6%
   Memory: 85.2%
   
   [SiteWiseTutorialDevice1]
   Update request e6686e44-fca0-44db-aa48-3ca81726f3e3 accepted
   ```

1. 請按照下列步驟，確認指令碼是否正在更新裝置陰影：

   1. 導覽至 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

   1. 在左側導覽窗格中，選擇**所有裝置**，然後選擇**實物**。

   1. 選擇您的物件 **SiteWiseTutorialDevice**。

   1. 選擇 **Device Shadows** 索引標籤，選擇 **Classic Shadow**，然後驗證 **Shadow 狀態**看起來如下範例所示。

      ```
      {
        "reported": {
          "cpu": 24.6,
          "memory": 85.2,
          "timestamp": 1579567542.2835066
        }
      }
      ```

      如果您物件的影子狀態為空，或看起來與上一個範例不同，請檢查指令碼是否正在執行並成功連線 AWS IoT。如果指令碼在連線至 時繼續逾時 AWS IoT，請檢查您的[物件政策](#ingestion-tutorial-create-iot-policy)是否已根據本教學課程設定。

1. 遵循下列步驟，確認規則動作是否正在將資料傳送到 AWS IoT SiteWise：

   1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)。

   1. 在左側導覽窗格中，選擇 **Assets (資產)**。

   1. 選擇裝置機群資產 (**SiteWise Tutorial Device Fleet 1**) 旁的箭頭以展開其資產階層，然後選擇您的裝置資產 (**SiteWise Tutorial Device 1**)。

   1. 選擇 **Measurements (衡量值)**。

   1. 確認 **Latest value (最新值)** 儲存格有 **CPU Usage** 和 **Memory Usage** 屬性的值。  
![\[螢幕擷取畫面反白顯示「測量」。\]](http://docs.aws.amazon.com/zh_tw/iot-sitewise/latest/userguide/images/rule-ingestion/sitewise-view-measurement-values-console.png)

   1. 如果 **CPU Usage** 和 **Memory Usage** 屬性沒有最新的值，請重新整理頁面。如果值在幾分鐘後未出現，請參閱[對規則進行故障診斷 (AWS IoT SiteWise)](troubleshoot-rule.md#rule-tutorial-troubleshoot-rule)。

您已完成本教學課程。若要探索資料的即時視覺效果，您可以在 AWS IoT SiteWise Monitor中設定入口網站。如需詳細資訊，請參閱[使用 監控資料 AWS IoT SiteWise Monitor](monitor-data.md)。否則，您可以在命令提示字元中按 **CTRL\$1C**，以停止裝置用戶端指令碼。Python 程式不太可能傳送足夠的訊息因而衍生費用，但最佳實務是在完成時停止程式。

## 步驟 9：在教學課程後清除資源
<a name="rule-tutorial-clean-up-resources"></a>

**注意**  
[整合資料至 SiteWise Edge](integrate_sitewise_edge_mqtt.md) 教學課程需要本教學課程中建立的資源。如果您打算完成，請勿清除此步驟中的資源。

完成從 AWS IoT 實物擷取資料的教學課程後，請清理您的資源，以避免產生額外費用。<a name="rule-tutorial-delete-assets"></a>

**在 中刪除階層式資產 AWS IoT SiteWise**

1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)

1. 在左側導覽窗格中，選擇 **Assets (資產)**。

1. 當您在 中刪除資產時 AWS IoT SiteWise，您必須先取消它們的關聯。

   完成下列步驟，以取消裝置資產與裝置機群資產的關聯：

   1. 選擇您的裝置機群資產 (**SiteWise Tutorial Device Fleet 1**)。

   1. 選擇**編輯**。

   1. 在 **Assets associated to this asset (與此資產相關聯的資產)** 底下，針對與此裝置機群資產相關聯的每個裝置資產選擇 **Disassociate (取消關聯)**。

   1. 選擇**儲存**。

      您現在應該會看到裝置資產不再整理為階層的形式。

1. 選擇裝置資產 (**SiteWise Tutorial Device 1**)。

1. 選擇 **刪除**。

1. 在確認對話方塊中輸入 **Delete**，然後選擇 **Delete (刪除)**。

1. 為每個裝置資產和裝置機群資產 () 重複步驟 4 到 6**SiteWise Tutorial Device Fleet 1**。

**在 中刪除階層式資產模型 AWS IoT SiteWise**

1. 導覽至 [AWS IoT SiteWise 主控台](https://console.aws.amazon.com/iotsitewise/)。

1. 如果您尚未刪除裝置和裝置機群資產，請執行此操作。如需詳細資訊，請參閱[上一個程序](#rule-tutorial-delete-assets)。如果您有已從該模型建立的資產，則無法刪除模型。

1. 在左側導覽窗格中選擇 **Models (模型)**。

1. 選擇裝置機群資產模型 (**SiteWise Tutorial Device Fleet Model 1**)。

   刪除階層資產模型時，請先刪除父資產模型。

1. 選擇 **刪除**。

1. 在確認對話方塊中輸入 **Delete**，然後選擇 **Delete (刪除)**。

1. 針對裝置資產模型 (**SiteWise Tutorial Device Model**) 重複步驟 4 到 6。

**在 中停用或刪除規則 AWS IoT Core**

1. 導覽至 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格中，選擇**訊息路由**，然後選擇**規則**。

1. 選取您的規則，然後選擇**刪除**。

1. 在確認對話方塊中，輸入規則的名稱，然後選擇**刪除**。