

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

# 使用您的 Windows 或 Linux PC 或 Mac 做為 AWS IoT 裝置
<a name="using-laptop-as-device"></a>

在本教學課程中，您將設定個人電腦以搭配 使用 AWS IoT。這些指示支援 Windows 和 Linux PC 以及 Mac。若要完成此目的，您需要在電腦上安裝一些軟體。如果您不想要在電腦上安裝軟體，則可以嘗試 [使用 Amazon EC2 建立虛擬裝置](creating-a-virtual-thing.md)，它會在虛擬機器上安裝所有軟體。

**Topics**
+ [設定您的個人電腦](#gs-pc-prereqs)
+ [安裝 Git、Python 和適用於 Python AWS IoT 的裝置 SDK](#gs-pc-sdk-node)
+ [設定政策和執行範例應用程式](#gs-pc-python-app-run)
+ [在 AWS IoT 主控台中檢視來自範例應用程式的訊息](#gs-pc-view-msg)
+ [在 Python 中執行共享訂閱範例](#gs-pc-shared-subscription-example)

## 設定您的個人電腦
<a name="gs-pc-prereqs"></a>

若要完成本教學課程，您需要一部 Windows 或 Linux PC，或是一部可連接到網際網路的 Mac。

繼續下一個步驟之前，請確定您可以在電腦上開啟命令列視窗。在 Windows PC 上使用 **cmd.exe**。在 Linux PC 或 Mac 上，使用 **Terminal**。

## 安裝 Git、Python 和適用於 Python AWS IoT 的裝置 SDK
<a name="gs-pc-sdk-node"></a>

在本節中，您將在電腦上安裝 Python 和適用於 Python 的 AWS IoT 裝置 SDK。

### 安裝最新版本的 Git 和 Python
<a name="gs-pc-node-runtime"></a>

此程序說明如何在個人電腦上安裝最新版本的 Git 和 Python。

**在您的電腦上下載並安裝 Git 和 Python**

1. 查看您的電腦上是否已安裝 Git。在命令列中輸入此命令。

   ```
   git --version
   ```

   如果命令顯示 Git 版本，表示已安裝 Git，而且您可以繼續進行下一個步驟。

   如果命令顯示錯誤，請開啟 [https://git-scm.com/download](https://git-scm.com/download) 並為您的電腦安裝 Git。

1. 查看您是否已安裝 Python。在命令列中輸入此命令。

   ```
   python -V
   ```
**注意**  
如果此命令提供錯誤：`Python was not found`，原因可能是您的作業系統呼叫 Python v3.x 可執行檔作為 `Python3`。在此情況下，將 `python` 的所有執行個體取代為 `python3`，並繼續進行本教學課程的其餘部分。

   如果命令顯示 Python 版本，則表示已安裝 Python。本教學課程需要 Python v3.7 或更新版本。

1. 如果已安裝 Python，則可以跳過本節的其餘步驟。如果未安裝，請繼續。

1. 開啟 [https://www.python.org/downloads/](https://www.python.org/downloads/)，並下載適用於您電腦的安裝程式。

1. 如果下載未自動開始安裝，請執行下載的程式來安裝 Python。

1. 驗證 Python 的安裝。

   ```
   python -V
   ```

   確認命令顯示 Python 版本。如果未顯示 Python 版本，請嘗試再次下載並安裝 Python。

### 安裝適用於 Python 的 AWS IoT 裝置 SDK
<a name="gs-pc-python-intall-sdk"></a>

**在電腦上安裝適用於 Python 的 AWS IoT 裝置 SDK**

1. 安裝適用於 Python 的 AWS IoT 裝置 SDK v2。

   ```
   python3 -m pip install awsiotsdk
   ```

1. 將適用於 Python 的 AWS IoT 裝置 SDK 儲存庫複製到主目錄的 aws-iot-device-sdk-python-v2 目錄中。此程序會將所安裝檔案的目錄稱為 *home*。

   *home* 目錄的實際位置取決於您的作業系統。

------
#### [ Linux/macOS ]

   在 macOS 和 Linux 中，*home* 目錄為 `~`。

   ```
   cd ~ 
   git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
   ```

------
#### [ Windows ]

   在 Windows 中，您可以在 `cmd` 視窗中執行此命令，來尋找 *home* 目錄路徑。

   ```
   echo %USERPROFILE%
   cd %USERPROFILE%
   git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
   ```

------
**注意**  
如果您是使用 Windows PowerShell，而不是 **cmd.exe**，則會使用下列命令。  

   ```
   echo $home
   ```

如需詳細資訊，請參閱[適用於 Python GitHub 儲存庫的AWS IoT 裝置 SDK](https://github.com/aws/aws-iot-device-sdk-python-v2)。

### 準備執行範例應用程式
<a name="gs-pc-python-config-app"></a>

**準備您的系統以執行範例應用程式**
+ 建立 `certs` 目錄。將下列項目複製至 `certs` 目錄：私有金鑰、裝置憑證，以及您在 [建立 AWS IoT 資源](create-iot-resources.md) 建立和註冊物件時所儲存的根憑證授權機構憑證檔案。目的地目錄中每個檔案的檔案名稱應與表格中的檔案名稱相符。

   下節命令假設您的金鑰和憑證檔案儲存在您的裝置上，如下表所示。

------
#### [ Linux/macOS ]

  執行此命令來建立 `certs` 子目錄，您會在執行範例應用程式時使用這個子目錄。

  ```
  mkdir ~/certs
  ```

  在新的子目錄中，將檔案複製到下表所示的目的地檔案路徑。  
**憑證檔案名稱**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/iot/latest/developerguide/using-laptop-as-device.html)

  執行此命令來列出 `certs` 目錄中的檔案，並將其與表格中列出的檔案進行比較。

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

------
#### [ Windows ]

  執行此命令來建立 `certs` 子目錄，您會在執行範例應用程式時使用這個子目錄。

  ```
  mkdir %USERPROFILE%\certs
  ```

  在新的子目錄中，將檔案複製到下表所示的目的地檔案路徑。  
**憑證檔案名稱**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/iot/latest/developerguide/using-laptop-as-device.html)

  執行此命令來列出 `certs` 目錄中的檔案，並將其與表格中列出的檔案進行比較。

  ```
  dir %USERPROFILE%\certs
  ```

------

## 設定政策和執行範例應用程式
<a name="gs-pc-python-app-run"></a>

在本節中，您會設定政策，並執行 `pubsub.py` 範例指令碼，其位於 適用於 Python 的 AWS IoT Device SDK的 `aws-iot-device-sdk-python-v2/samples` 目錄中。此指令碼顯示您的裝置如何使用 MQTT 程式庫來發佈和訂閱 MQTT 訊息。

`pubsub.py` 範例應用程式會訂閱主題 `test/topic`、將 10 則訊息發佈至該主題，以及在從訊息代理程式接收訊息時顯示這些訊息。

若要執行 `pubsub.py` 範例指令碼，您需要以下資訊：


**應用程式參數值**  

|  參數  |  可在哪裡找到值  | 
| --- | --- | 
| your-iot-endpoint |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/iot/latest/developerguide/using-laptop-as-device.html)  | 

*your-iot-endpoint* 值的格式為：`endpoint_id-ats.iot.region.amazonaws.com`，例如 `a3qj468EXAMPLE-ats.iot.us-west-2.amazonaws.com`。

執行指令碼之前，請確定您物件的政策許可範例指令碼連接、訂閱、發佈和接收。

**尋找並檢閱物件資源的政策文件**

1. 在 [AWS IoT 主控台](https://console.aws.amazon.com//iot/home#/thinghub)的 **Things** (物件) 清單中，尋找代表您裝置的資源。

1. 選擇代表您裝置物件資源的 **Name** (名稱) 連結，以開啟 **Thing details** (物件詳細資訊) 頁面。

1. 在 **Thing details** (物件詳細資訊) 頁面中的 **Certificates** (憑證) 索引標籤上，選擇與物件資源相連的憑證。清單中應該只有一個憑證。如果有一個以上的憑證，請選擇其檔案已安裝在裝置上且將用來連接至 AWS IoT Core的憑證。

   於 **Certificate** (憑證) 詳細資訊頁面的 **Policies** (政策) 索引標籤中，選擇與憑證相連的政策。其中應只有一個政策。如果有多個政策，請針對每個政策重複下一個步驟，以確保至少有一個政策授予必要的存取權。

1. 在 **Policy** (政策) 概觀頁面中，找到 JSON 編輯器並選擇 **Edit policy document** (編輯政策文件)，視需要檢閱和編輯政策文件。

1. 政策 JSON 會顯示在下列範例中。在 `"Resource"`元素中，將 取代`region:account`為每個`Resource`值 AWS 帳戶 中的 AWS 區域 和 。  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Publish",
                   "iot:Receive"
               ],
               "Resource": [
               "arn:aws:iot:us-east-1:123456789012:topic/test/topic"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Subscribe"
               ],
               "Resource": [
               "arn:aws:iot:us-east-1:123456789012:topicfilter/test/topic"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Connect"
               ],
               "Resource": [
               "arn:aws:iot:us-east-1:123456789012:client/test-*"
               ]
           }
       ]
   }
   ```

------
#### [ Linux/macOS ]

**在 Linux/macOS 上執行範本指令碼**

1. 在命令列視窗中，導覽至 SDK 使用這些命令所建立的 `~/aws-iot-device-sdk-python-v2/samples/node/pub_sub` 目錄。

   ```
   cd ~/aws-iot-device-sdk-python-v2/samples
   ```

1. 在您的命令列視窗中，按照指示取代 *your-iot-endpoint* 並執行此命令。

   ```
   python3 pubsub.py --endpoint your-iot-endpoint --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key
   ```

------
#### [ Windows ]

**在 Windows PC 上執行範例應用程式**

1. 在命令列視窗中，導覽至 SDK 所建立的 `%USERPROFILE%\aws-iot-device-sdk-python-v2\samples` 目錄，然後使用這些命令來安裝範例應用程式。

   ```
   cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples
   ```

1. 在您的命令列視窗中，按照指示取代 *your-iot-endpoint* 並執行此命令。

   ```
   python3 pubsub.py --endpoint your-iot-endpoint --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key
   ```

------

範例指令碼：

1. 連線至 AWS IoT Core 您帳戶的 。

1. 訂閱訊息主題 **test/topic**，並顯示其收到關於該主題的訊息。

1. 將 10 則訊息發佈至主題 **test/topic**。

1. 顯示類似下列內容的輸出：

```
Connected!
Subscribing to topic 'test/topic'...
Subscribed with QoS.AT_LEAST_ONCE
Sending 10 message(s)
Publishing message to topic 'test/topic': Hello World! [1]
Received message from topic 'test/topic': b'"Hello World! [1]"'
Publishing message to topic 'test/topic': Hello World! [2]
Received message from topic 'test/topic': b'"Hello World! [2]"'
Publishing message to topic 'test/topic': Hello World! [3]
Received message from topic 'test/topic': b'"Hello World! [3]"'
Publishing message to topic 'test/topic': Hello World! [4]
Received message from topic 'test/topic': b'"Hello World! [4]"'
Publishing message to topic 'test/topic': Hello World! [5]
Received message from topic 'test/topic': b'"Hello World! [5]"'
Publishing message to topic 'test/topic': Hello World! [6]
Received message from topic 'test/topic': b'"Hello World! [6]"'
Publishing message to topic 'test/topic': Hello World! [7]
Received message from topic 'test/topic': b'"Hello World! [7]"'
Publishing message to topic 'test/topic': Hello World! [8]
Received message from topic 'test/topic': b'"Hello World! [8]"'
Publishing message to topic 'test/topic': Hello World! [9]
Received message from topic 'test/topic': b'"Hello World! [9]"'
Publishing message to topic 'test/topic': Hello World! [10]
Received message from topic 'test/topic': b'"Hello World! [10]"'
10 message(s) received.
Disconnecting...
Disconnected!
```

若在執行範例應用程式時發生問題，請檢閱 [對範例應用程式的問題進行故障診斷](gs-device-troubleshoot.md)。

您也可以將 `--verbosity Debug` 參數新增至命令列，以便範例應用程式顯示有關其正在做什麼的詳細訊息。該資訊可能會協助您更正問題。

## 在 AWS IoT 主控台中檢視來自範例應用程式的訊息
<a name="gs-pc-view-msg"></a>

您可以在範例應用程式的訊息透過訊息代理程式傳遞時看到這些訊臮，方法為使用 **AWS IoT 主控台**中的 **MQTT test client** (MQTT 測試用戶端)。

**檢視範例應用程式所發佈的 MQTT 訊息**

1. 檢閱 [使用 MQTT 用戶端檢視 AWS IoT MQTT 訊息](view-mqtt-messages.md)。這有助於您了解如何使用 **AWS IoT 主控台**中的 **MQTT 測試用戶端**，在 MQTT 訊息通過訊息代理程式時，檢視訊息。

1. 在 **AWS IoT 主控台**中開啟 **MQTT 測試用戶端**。

1. 在 **Subscribe to a topic** (訂閱主題) 中，訂閱主題 **test/topic**。

1. 在您的命令列視窗中，再次執行範例應用程式，並在 **AWS IoT 主控台**的 **MQTT client** (MQTT 用戶端) 中觀看訊息。

------
#### [ Linux/macOS ]

   ```
   cd ~/aws-iot-device-sdk-python-v2/samples
   python3 pubsub.py --topic test/topic --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

------
#### [ Windows ]

   ```
   cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples
   python3 pubsub.py --topic test/topic --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key --endpoint your-iot-endpoint
   ```

------

如需 MQTT 和 如何 AWS IoT Core 支援通訊協定的詳細資訊，請參閱 [MQTT](https://docs.aws.amazon.com//iot/latest/developerguide/mqtt.html)。

## 在 Python 中執行共享訂閱範例
<a name="gs-pc-shared-subscription-example"></a>

AWS IoT Core 同時支援 MQTT 3 和 MQTT 5 [的共用訂閱](mqtt.md#mqtt5-shared-subscription)。共享訂閱允許多個用戶端共享一個主題的訂閱，而且只有一個用戶端會使用隨機分佈接收發佈至該主題的訊息。若要使用共享訂閱，用戶端會訂閱共享訂閱的[主題篩選條件](https://docs.aws.amazon.com//iot/latest/developerguide/topics.html#topicfilters)：`$share/{ShareName}/{TopicFilter}`。

**設定政策並執行共享訂閱範例**

1. 若要執行共享訂閱範例，您必須依照 [MQTT 5 共享訂閱](https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/samples/mqtt5_shared_subscription.md#mqtt5-shared-subscription)中所述來設定物件的政策。

1. 若要執行共享訂閱，請執行下列命令。

------
#### [ Linux/macOS ]

**在 Linux/macOS 上執行範本指令碼**

   1. 在命令列視窗中，導覽至 SDK 使用這些命令所建立的 `~/aws-iot-device-sdk-python-v2/samples` 目錄。

      ```
      cd ~/aws-iot-device-sdk-python-v2/samples
      ```

   1. 在您的命令列視窗中，按照指示取代 *your-iot-endpoint* 並執行此命令。

      ```
      python3 mqtt5_shared_subscription.py --endpoint your-iot-endpoint --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --group_identifier consumer
      ```

------
#### [ Windows ]

**在 Windows PC 上執行範例應用程式**

   1. 在命令列視窗中，導覽至 SDK 所建立的 `%USERPROFILE%\aws-iot-device-sdk-python-v2\samples` 目錄，然後使用這些命令來安裝範例應用程式。

      ```
      cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples
      ```

   1. 在您的命令列視窗中，按照指示取代 *your-iot-endpoint* 並執行此命令。

      ```
      python3 mqtt5_shared_subscription.py --endpoint your-iot-endpoint --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key --group_identifier consumer
      ```

------
**注意**  
執行範例 (例如 `--group_identifier consumer`) 時，您可以根據需求選擇性地指定群組識別碼。如果您沒有指定一個，則 `python-sample` 是預設群組識別碼。

1. 此命令列的輸出如下所示：

   ```
   Publisher]: Lifecycle Connection Success
   [Publisher]: Connected
   Subscriber One]: Lifecycle Connection Success
   [Subscriber One]: Connected
   Subscriber Two]: Lifecycle Connection Success
   [Subscriber Two]: Connected
   [Subscriber One]: Subscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber One]: Full subscribed topic is: '$share/consumer/test/topic' with SubAck code: [<SubackReasonCode.GRANTED_QOS_1: 1>]
   [Subscriber Two]: Subscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber Two]: Full subscribed topic is: '$share/consumer/test/topic' with SubAck code: [<SubackReasonCode.GRANTED_QOS_1: 1>]
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [1]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [2]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [3]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [4]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [5]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [6]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [7]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [8]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [9]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [10]"'
   [Subscriber One]: Unsubscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber One]: Full unsubscribed topic is: '$share/consumer/test/topic' with UnsubAck code: [<UnsubackReasonCode.SUCCESS: 0>]
   [Subscriber Two]: Unsubscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber Two]: Full unsubscribed topic is: '$share/consumer/test/topic' with UnsubAck code [<UnsubackReasonCode.SUCCESS: 0>]
   Publisher]: Lifecycle Disconnected
   [Publisher]: Lifecycle Stopped
   [Publisher]: Fully stopped
   Subscriber One]: Lifecycle Disconnected
   [Subscriber One]: Lifecycle Stopped
   [Subscriber One]: Fully stopped
   Subscriber Two]: Lifecycle Disconnected
   [Subscriber Two]: Lifecycle Stopped
   [Subscriber Two]: Fully stopped
   Complete!
   ```

1. 在 **AWS IoT 主控台**中開啟 **MQTT 測試用戶端**。在**訂閱主題**中，訂閱共享訂閱的主題，例如：`$share/consumer/test/topic`。執行範例 (例如 `--group_identifier consumer`) 時，您可以根據需求指定群組識別碼。如果您未指定群組識別碼，則預設值為 `python-sample`。如需詳細資訊，請參閱來自《AWS IoT Core 開發人員指南》**中的 [MQTT 5 共享訂閱 Python 範例](https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/samples/mqtt5_shared_subscription.md#mqtt5-shared-subscription)和[共享訂閱](mqtt.md#mqtt5-shared-subscription)。

   在您的命令列視窗中，再次執行範例應用程式，並在 **AWS IoT 主控台**的 **MQTT 測試用戶端**，以及命令列中觀看訊息的分佈。  
![\[共用訂閱輸出頁面。\]](http://docs.aws.amazon.com/zh_tw/iot/latest/developerguide/images/shared-subscription-output.png)