

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

# 準備 Raspberry Pi 以示範 MQTT 訊息通訊
<a name="iot-dc-testconn-provision"></a>

此程序會在 Raspberry Pi 中 AWS IoT 和 中建立資源，以使用 AWS IoT 裝置用戶端示範 MQTT 訊息通訊。

**Topics**
+ [建立憑證檔案來示範 MQTT 通訊](#iot-dc-testconn-provision-certs)
+ [佈建裝置來示範 MQTT 通訊](#iot-dc-testconn-provision-aws)
+ [設定 AWS IoT Device Client 組態檔案和 MQTT 測試用戶端，以示範 MQTT 通訊](#iot-dc-testconn-provision-dc-config)

## 建立憑證檔案來示範 MQTT 通訊
<a name="iot-dc-testconn-provision-certs"></a>

此程序會建立此示範的裝置憑證檔案。

**為 Raspberry Pi 建立並下載裝置憑證檔案**



1. 在本機主機電腦的終端機視窗中輸入下列命令，為裝置建立裝置憑證檔案。

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

   此命令會傳回類似以下的回應。儲存 `{{certificateArn}}` 值，供之後使用。

   ```
   {
   "certificateArn": "{{arn:aws:iot:us-west-2:57EXAMPLE833:cert/76e7e4edb3e52f52334be2f387a06145b2aa4c7fcd810f3aea2d92abc227d269}}",
   "certificateId": "76e7e4edb3e52f5233EXAMPLE7a06145b2aa4c7fcd810f3aea2d92abc227d269",
   "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDWTCCAkGgAwIBAgI_SHORTENED_FOR_EXAMPLE_Lgn4jfgtS\n-----END CERTIFICATE-----\n",
   "keyPair": {
       "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BA_SHORTENED_FOR_EXAMPLE_ImwIDAQAB\n-----END PUBLIC KEY-----\n",
       "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQE_SHORTENED_FOR_EXAMPLE_T9RoDiukY\n-----END RSA PRIVATE KEY-----\n"
   }
   }
   ```

1. 輸入下列命令來設定憑證目錄及其檔案的許可。

   ```
   chmod 700 ~/certs/pubsub
   chmod 644 ~/certs/pubsub/*
   chmod 600 ~/certs/pubsub/private.pem.key
   ```

1. 執行此命令來檢閱憑證目錄和檔案的許可。

   ```
   ls -l ~/certs/pubsub
   ```

   命令的輸出應該與您在此處看到的相同，但檔案日期和時間會有所不同。

   ```
   -rw-r--r-- 1 pi pi 1220 Oct 28 13:02 device.pem.crt
   -rw------- 1 pi pi 1675 Oct 28 13:02 private.pem.key
   -rw-r--r-- 1 pi pi  451 Oct 28 13:02 public.pem.key
   ```

1. 輸入這些命令來建立記錄檔案的目錄。

   ```
   mkdir ~/.aws-iot-device-client
   mkdir ~/.aws-iot-device-client/log
   chmod 745 ~/.aws-iot-device-client/log
   echo " " > ~/.aws-iot-device-client/log/aws-iot-device-client.log
   echo " " > ~/.aws-iot-device-client/log/pubsub_rx_msgs.log
   chmod 600 ~/.aws-iot-device-client/log/*
   ```

## 佈建裝置來示範 MQTT 通訊
<a name="iot-dc-testconn-provision-aws"></a>

本節會建立在 中佈建 Raspberry Pi AWS IoT 的資源 AWS IoT。

**若要在 AWS IoT中佈建裝置：**

1. 在本機主機電腦的終端機視窗中輸入下列命令，取得 AWS 帳戶裝置資料端點的地址。

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

   自您依照上一個教學課程執行此命令後，端點值便未發生變更。此處再次執行命令是為了輕鬆找到資料端點值並將其貼入本教學課程中使用的組態檔。

   先前步驟的命令會傳回類似以下的回應：記錄 `{{endpointAddress}}` 值，供之後使用。

   ```
   {
   "endpointAddress": "{{a3qjEXAMPLEffp-ats.iot.us-west-2.amazonaws.com}}"
   }
   ```

1. 輸入此命令來為您的 Raspberry Pi 建立新的 AWS IoT 物件資源。

   ```
   aws iot create-thing --thing-name "PubSubTestThing"
   ```

   由於 AWS IoT 物件資源是您在雲端中裝置的*虛擬*表示法，因此我們可以在 中建立多個物件資源 AWS IoT ，以用於不同的用途。這些資源都可以由同一個實體 IoT 裝置使用，用以代表裝置的不同面向。

   這些教學課程一次只會使用一個物件資源來表示 Raspberry Pi。如此一來，在這些教學課程中，它們代表不同的示範，因此在您為示範建立 AWS IoT 資源之後，您可以返回並使用您專門為每個示範建立的資源重複示範。

   如果您的 AWS IoT 物件資源已建立，命令會傳回類似這樣的回應。

   ```
   {
   "thingName": "PubSubTestThing",
   "thingArn": "arn:aws:iot:us-west-2:57EXAMPLE833:thing/PubSubTestThing",
   "thingId": "8ea78707-32c3-4f8a-9232-14bEXAMPLEfd"
   }
   ```

1. 在終端機視窗中：

   1. 開啟文字編輯器，例如 `nano`。

   1. 複製此 JSON 文件並將其貼入開啟的文字編輯器中。  
****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "iot:Connect"
                  ],
                  "Resource": [
                      "arn:aws:iot:{{us-west-2:123456789012}}:client/PubSubTestThing"
                  ]
              },
              {
                  "Effect": "Allow",
                  "Action": [
                      "iot:Publish"
                  ],
                  "Resource": [
                      "arn:aws:iot:{{us-west-2:123456789012}}:topic/test/dc/pubtopic"
                  ]
              },
              {
                  "Effect": "Allow",
                  "Action": [
                      "iot:Subscribe"
                  ],
                  "Resource": [
                      "arn:aws:iot:{{us-west-2:123456789012}}:topicfilter/test/dc/subtopic"
                  ]
              },
              {
                  "Effect": "Allow",
                  "Action": [
                      "iot:Receive"
                  ],
                  "Resource": [
                      "arn:aws:iot:{{us-west-2:123456789012}}:topic/test/dc/subtopic"
                  ]
              }
          ]
      }
      ```

   1. 在編輯器中，在政策文件的每個`Resource`區段中，將 {{us-west-2：57EXAMPLE833}} 取代為 AWS 區域、冒號字元 (：) 和 12 位數字 AWS 帳戶 。

   1. 將文字編輯器中的檔案儲存為 **\~/policies/pubsub\_test\_thing\_policy.json**。

1. 執行此命令以使用先前步驟中的政策文件來建立 AWS IoT 政策。

   ```
   aws iot create-policy \
   --policy-name "PubSubTestThingPolicy" \
   --policy-document "file://~/policies/pubsub_test_thing_policy.json"
   ```

   如果建立此政策，此命令會傳回類似以下的回應。

   ```
   {
                                       "policyName": "PubSubTestThingPolicy",
                                       "policyArn": "arn:aws:iot:us-west-2:57EXAMPLE833:policy/PubSubTestThingPolicy",
                                       "policyDocument": "{\n\"Version\": \"2012-10-17\",		 	 	 \n\"Statement\": [\n{\n\"Effect\": \"Allow\",\n\"Action\": [\n\"iot:Connect\"\n],\n\"Resource\": [\n\"arn:aws:iot:us-west-2:57EXAMPLE833:client/PubSubTestThing\"\n]\n},\n{\n\"Effect\": \"Allow\",\n\"Action\": [\n\"iot:Publish\"\n],\n\"Resource\": [\n\"arn:aws:iot:us-west-2:57EXAMPLE833:topic/test/dc/pubtopic\"\n]\n},\n{\n\"Effect\": \"Allow\",\n\"Action\": [\n\"iot:Subscribe\"\n],\n\"Resource\": [\n\"arn:aws:iot:us-west-2:57EXAMPLE833:topicfilter/test/dc/subtopic\"\n]\n},\n{\n\"Effect\": \"Allow\",\n\"Action\": [\n\"iot:Receive\"\n],\n\"Resource\": [\n\"arn:aws:iot:us-west-2:57EXAMPLE833:topic/test/dc/*\"\n]\n}\n]\n}\n",
                                       "policyVersionId": "1"
                                       }
   ```

1. 執行此命令，將此政策連接至裝置憑證。使用之前在本節儲存的 `certificateArn` 值來取代 `{{certificateArn}}`

   ```
   aws iot attach-policy \
   --policy-name "PubSubTestThingPolicy" \
   --target "{{certificateArn}}"
   ```

   若成功，此命令不會傳回任何內容。

1. 執行此命令，將裝置憑證連接至 AWS IoT 物件資源。使用之前在本節儲存的 `certificateArn` 值來取代 `{{certificateArn}}`

   ```
   aws iot attach-thing-principal \
   --thing-name "PubSubTestThing" \
   --principal "{{certificateArn}}"
   ```

   若成功，此命令不會傳回任何內容。

成功在 中佈建裝置後 AWS IoT，您就可以繼續 [設定 AWS IoT Device Client 組態檔案和 MQTT 測試用戶端，以示範 MQTT 通訊](#iot-dc-testconn-provision-dc-config)。

## 設定 AWS IoT Device Client 組態檔案和 MQTT 測試用戶端，以示範 MQTT 通訊
<a name="iot-dc-testconn-provision-dc-config"></a>

此程序會建立組態檔案來測試 AWS IoT 裝置用戶端。

**建立組態檔案以測試 AWS IoT 裝置用戶端**

1. 在連接至 Raspberry Pi 本機主機電腦上的終端機視窗中：

   1. 開啟文字編輯器，例如 `nano`。

   1. 複製此 JSON 文件並將其貼入開啟的文字編輯器中。

      ```
      {
        "endpoint": "{{a3qEXAMPLEaffp-ats.iot.us-west-2.amazonaws.com}}",
        "cert": "~/certs/pubsub/device.pem.crt",
        "key": "~/certs/pubsub/private.pem.key",
        "root-ca": "~/certs/AmazonRootCA1.pem",
        "thing-name": "PubSubTestThing",
        "logging": {
          "enable-sdk-logging": true,
          "level": "DEBUG",
          "type": "STDOUT",
          "file": ""
        },
        "jobs": {
          "enabled": false,
          "handler-directory": ""
        },
        "tunneling": {
          "enabled": false
        },
        "device-defender": {
          "enabled": false,
          "interval": 300
        },
        "fleet-provisioning": {
          "enabled": false,
          "template-name": "",
          "template-parameters": "",
          "csr-file": "",
          "device-key": ""
        },
        "samples": {
          "pub-sub": {
            "enabled": true,
            "publish-topic": "test/dc/pubtopic",
            "publish-file": "",
            "subscribe-topic": "test/dc/subtopic",
            "subscribe-file": "~/.aws-iot-device-client/log/pubsub_rx_msgs.log"
          }
        },
        "config-shadow": {
          "enabled": false
        },
        "sample-shadow": {
          "enabled": false,
          "shadow-name": "",
          "shadow-input-file": "",
          "shadow-output-file": ""
        }
      }
      ```

   1. 將{{端點}}值取代為您 AWS 帳戶 在 中找到之 的裝置資料端點[在 中佈建您的裝置 AWS IoT Core](iot-dc-install-provision.md#iot-dc-install-dc-provision)。

   1. 將文字編輯器中的檔案儲存為 **\~/dc-configs/dc-pubsub-config.json**。

   1. 執行此命令來設定新組態檔的許可。

      ```
      chmod 644 ~/dc-configs/dc-pubsub-config.json
      ```

1. 若要準備 **MQTT test client** (MQTT 測試用戶端) 來訂閱所有 MQTT 訊息：

   1. 在 [AWS IoT 主控台](https://console.aws.amazon.com//iot/home#/test)的本機主機電腦上，選擇 **MQTT test client** (MQTT 測試用戶端)。

   1. 在 **Subscribe to a topic** (訂閱主題) 索引標籤的 **Topic filter** (主題篩選條件) 中，輸入 **\#** (單個井字符號)，然後選擇 **Subscribe** (訂閱)。

   1. 在 **Subscriptions** (訂閱) 標籤下方，請確認看到 **\#** (單個井字符號)。

   在繼續進行此教學課程時，請讓有 **MQTT test client** (MQTT 測試用戶端) 的視窗保持開啟。

在儲存檔案並設定 **MQTT test client** (MQTT 測試用戶端)之後，您就可以繼續進行 [示範使用 AWS IoT 裝置用戶端發佈訊息](iot-dc-testconn-publish.md)。