

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

# 教學課程：列出 AWS IoT SiteWise Edge 閘道上的資產模型
<a name="edge-apis-tutorial"></a>

您可以使用一部分的可用 AWS IoT SiteWise APIs 以及邊緣特定的 APIs，與邊緣上的資產模型及其資產互動。本教學課程將逐步引導您取得 AWS IoT SiteWise Edge 閘道的臨時登入資料，以及 SiteWise Edge 閘道上的資產模型清單。

## 先決條件
<a name="edge-apis-tutorial-prerequisites"></a>

在本教學課程中，您可以使用各種工具。若要使用這些工具，請確定已安裝對應的先決條件。

為了完成本教學，您需要以下項目：
+ 部署和執行中的 [AWS IoT SiteWise Edge 自我託管閘道需求](configure-gateway-ggv2.md)
+ 透過連接埠 443 存取相同網路中的 SiteWise Edge 閘道。
+ 已安裝 [OpenSSL](https://www.openssl.org/) 
+ (AWS OpsHub 適用於 AWS IoT SiteWise) [AWS OpsHubAWS IoT SiteWise 應用程式的](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)
+ 已安裝 (curl) [curl](https://ec.haxx.se/install/) 
+ 已安裝 (Python) [urllib3](https://urllib3.readthedocs.io/en/stable/index.html) 
+ (Python) 已安裝 [Python3](https://www.python.org/downloads/) 
+ (Python) 已安裝 [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 
+ (Python) 已安裝 [BotoCore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html) 

## 步驟 1：取得 SiteWise Edge 閘道服務簽署的憑證
<a name="edge-apis-tutorial-gateway-cert"></a>

若要建立與 SiteWise Edge 閘道上可用 APIs的 TLS 連線，您需要信任的憑證。您可以使用 OpenSSL 或 AWS OpsHub 產生此憑證 AWS IoT SiteWise。

------
#### [ OpenSSL ]

**注意**  
您需要安裝 [OpenSSL](https://www.openssl.org/) 才能執行此命令。

開啟終端機並執行下列命令，從 SiteWise Edge 閘道取得已簽署的憑證。`<sitewise_gateway_ip>` 將 取代為 SiteWise Edge 閘道的 IP。

```
openssl s_client -connect <sitewise_gateway_ip>:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > GatewayCert.pem
```

------
#### [ AWS OpsHub for AWS IoT SiteWise ]

您可以使用 AWS OpsHub AWS IoT SiteWise。如需詳細資訊，請參閱[管理 SiteWise Edge 閘道](manage-gateways-ggv2.md)。

------

本教學課程使用已下載 SiteWise Edge 閘道憑證的絕對路徑。執行下列命令以匯出憑證的完整路徑，將 取代`<absolute_path_to_certificate>`為憑證的路徑：

```
export PATH_TO_CERTIFICATE='<absolute_path_to_certificate>'
```

## 步驟 2：取得 SiteWise Edge 閘道主機名稱
<a name="edge-apis-tutorial-gateway-hostname"></a>

**注意**  
您需要安裝 [OpenSSL](https://www.openssl.org/) 才能執行此命令。

若要完成教學課程，您需要 SiteWise Edge 閘道的主機名稱。若要取得 SiteWise Edge 閘道的主機名稱，請執行下列動作，`<sitewise_gateway_ip>`將 取代為 SiteWise Edge 閘道的 IP：

```
openssl s_client -connect <sitewise_gateway_ip>:443 </dev/null 2>/dev/null | grep -Po 'CN = \K.*'| head -1
```

執行下列命令以匯出主機名稱以供日後使用，`<your_edge_gateway_hostname>`將 取代為 SiteWise Edge 閘道的主機名稱：

```
export GATEWAY_HOSTNAME='<your_edge_gateway_hostname>'
```

## 步驟 3：取得 SiteWise Edge 閘道的臨時登入資料
<a name="edge-apis-tutorial-temporary-credentials"></a>

現在您已擁有已簽署的憑證和 SiteWise Edge 閘道的主機名稱，您需要取得暫時憑證，才能在閘道上執行 APIs。您可以透過 取得這些登入資料， AWS OpsHub AWS IoT SiteWise 或使用 APIs 直接從 SiteWise Edge 閘道取得這些登入資料。

**重要**  
登入資料每隔 4 小時過期，因此您應該在 SiteWise Edge 閘道上使用 APIs之前取得登入資料。請勿快取登入資料超過 4 小時。

### 使用 AWS OpsHub for 取得臨時登入資料 AWS IoT SiteWise
<a name="edge-apis-tutorial-temp-creds-opshub"></a>

**注意**  
您需要安裝[AWS OpsHubAWS IoT SiteWise 應用程式的 ](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)。

若要使用 AWS OpsHub 讓 AWS IoT SiteWise 應用程式取得您的臨時登入資料，請執行下列動作：

1. 登入應用程式。

1. 選擇**設定**。

1. 針對**身分驗證**，選擇**複製登入**資料。

1. 展開適合您環境的選項，然後選擇**複製**。

1. 儲存登入資料以供日後使用。

### 使用 SiteWise Edge 閘道 API 取得臨時憑證
<a name="edge-apis-tutorial-temp-creds-api"></a>

若要使用 SiteWise Edge 閘道 API 取得您可以使用 Python 指令碼或 curl 的臨時登入資料，您必須先擁有 SiteWise Edge 閘道的使用者名稱和密碼。SiteWise Edge 閘道使用 SigV4 身分驗證和授權。如需新增使用者的詳細資訊，請參閱 [LDAP](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app) 或 [Linux 使用者集區](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)。這些登入資料將用於下列步驟，以在 SiteWise Edge 閘道上取得使用 AWS IoT SiteWise APIs。

------
#### [ Python ]

**注意**  
您需要安裝 [urllib3](https://urllib3.readthedocs.io/en/stable/index.html) 和 [Python3](https://www.python.org/downloads/)。

**使用 Python 取得登入資料**

1. 建立名為 **get\$1credentials.py** 的檔案，並將下列程式碼複製到其中。

   ```
   '''
   The following demonstrates how to get the credentials from the SiteWise Edge gateway. You will need to add local users or connect your system to LDAP/AD
   https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#create-user-pool
   
   Example usage:
       python3 get_credentials.py -e https://<gateway_hostname> -c <path_to_certificate> -u '<gateway_username>' -p '<gateway_password>' -m '<method>'
   '''
   import urllib3
   import json
   import urllib.parse
   import sys
   import os
   import getopt
   
   """
   This function retrieves the AWS IoT SiteWise Edge gateway credentials.
   """
   def get_credentials(endpoint,certificatePath, user, password, method):
       http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs= certificatePath)
       encoded_body = json.dumps({
           "username": user,
           "password": password,
           "authMechanism": method,
       })
   
       url =  urllib.parse.urljoin(endpoint, "/authenticate")
   
       response = http.request('POST', url,
           headers={'Content-Type': 'application/json'}, 
           body=encoded_body)
       
       if response.status != 200:
           raise Exception(f'Failed to authenticate! Response status {response.status}')
   
       auth_data = json.loads(response.data.decode('utf-8'))
   
       accessKeyId = auth_data["accessKeyId"]
       secretAccessKey = auth_data["secretAccessKey"]
       sessionToken = auth_data["sessionToken"]
       region = "edge"
   
       return accessKeyId, secretAccessKey, sessionToken, region
   
   def print_help():
       print('Usage:')
       print(f'{os.path.basename(__file__)} -e <endpoint> -c <path/to/certificate> -u <user> -p <password> -m <method> -a <alias>')
       print('')
       print('-e, --endpoint   edge gateway endpoint. Usually the Edge gateway hostname.')
       print('-c, --cert_path path to downloaded gateway certificate')
       print('-u, --user       Edge user')
       print('-p, --password   Edge password')
       print('-m, --method     (Optional) Authentication method (linux, winnt, ldap), default is linux')
       sys.exit()
   
   
   def parse_args(argv):
       endpoint = ""
       certificatePath = None
       user = None
       password = None
       method = "linux"
       
       try:
           opts, args = getopt.getopt(argv, "he:c:u:p:m:", ["endpoint=","cert_path=", "user=", "password=", "method="])
       except getopt.GetoptError:
           print_help()
   
       for opt, arg in opts:
           if opt == '-h':
               print_help()
           elif opt in ("-e", "--endpoint"):
               endpoint = arg
           elif opt in ("-u", "--user"):
               user = arg
           elif opt in ("-p", "--password"):
               password = arg
           elif opt in ("-m", "--method"):
               method = arg.lower()
           elif opt in ("-c", "--cert_path"):
               certificatePath = arg
   
       if method not in ['ldap', 'linux', 'winnt']:
           print("not valid method parameter, required are ldap, linux, winnt")
           print_help()
   
       if (user == None or password == None):
           print("To authenticate against edge user, password have to be passed together, and the region has to be set to 'edge'")
           print_help()
       
       if(endpoint == ""):
           print("You must provide a valid and reachable gateway hostname")
           print_help()
   
       return endpoint,certificatePath, user, password, method
   
   
   def main(argv):
       # get the command line args
       endpoint, certificatePath, user, password, method = parse_args(argv)
       
       accessKeyId, secretAccessKey, sessionToken, region=get_credentials(endpoint, certificatePath, user, password, method)
   
       print("Copy and paste the following credentials into the shell, they are valid for 4 hours:")
       print(f"export AWS_ACCESS_KEY_ID={accessKeyId}")
       print(f"export AWS_SECRET_ACCESS_KEY={secretAccessKey}")
       print(f"export AWS_SESSION_TOKEN={sessionToken}")
       print(f"export AWS_REGION={region}")
       print()
       
       
       
   
   if __name__ == "__main__":
      main(sys.argv[1:])
   ```

1. 從終端機使用您建立`<gateway_password>`的登入資料取代 `<gateway_username>`和 ，執行 **get\$1credentials.py**。

   ```
   python3 get_credentials.py -e https://$GATEWAY_HOSTNAME -c $PATH_TO_CERTIFICATE -u '<gateway_username>' -p '<gateway_password>' -m 'linux'
   ```

------
#### [ curl ]

**注意**  
您需要安裝 [curl](https://ec.haxx.se/install/)。

**使用 curl 取得登入資料**

1. 從終端機執行下列命令，將 <gateway\$1username> 和 <gateway\$1password> 取代為您建立的登入資料。

   ```
   curl --cacert $PATH_TO_CERTIFICATE --location \
   -X POST https://$GATEWAY_HOSTNAME:443/authenticate \
   --header 'Content-Type: application/json' \
   --data-raw '{
       "username": "<gateway_username>",
       "password": "<gateway_password>",
       "authMechanism": "linux"
   }'
   ```

   回應應如下所示：

   ```
   {
       "username": "sweuser",
       "accessKeyId": "<accessKeyId>",
       "secretAccessKey": "<secretAccessKey>",
       "sessionToken": "<sessionToken>",
       "sessionExpiryTime": "2022-11-17T04:51:40.927095Z",
       "authMechanism": "linux",
       "role": "edge-user"
   }
   ```

1. 從您的終端機中執行下列命令。

   ```
   export AWS_ACCESS_KEY_ID=<accessKeyId>
   export AWS_SECRET_ACCESS_KEY=<secretAccessKey>
   export AWS_SESSION_TOKEN=<sessionToken>
   export AWS_REGION=edge
   ```

------

## 步驟 4：取得 SiteWise Edge 閘道上的資產模型清單
<a name="edge-apis-tutorial-get-asset-models"></a>

現在您已擁有已簽署的憑證、SiteWise Edge 閘道主機名稱和 SiteWise Edge 閘道的臨時憑證，您可以使用 `ListAssetModels` API 取得 SiteWise Edge 閘道上的資產模型清單。

------
#### [ Python ]

**注意**  
您需要安裝 [Python3](https://www.python.org/downloads/)、[Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 和 [BotoCore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html)。

**使用 Python 取得資產模型的清單**

1. 建立名為 **list\$1asset\$1model.py** 的檔案，並將下列程式碼複製到其中。

   ```
   import json
   import boto3
   import botocore
   import os
   
   # create the client using the credentials
   client = boto3.client("iotsitewise", 
       endpoint_url= "https://"+ os.getenv("GATEWAY_HOSTNAME"),
       region_name=os.getenv("AWS_REGION"), 
       aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), 
       aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"), 
       aws_session_token=os.getenv("AWS_SESSION_TOKEN"),
       verify=os.getenv("PATH_TO_CERTIFICATE"),
       config=botocore.config.Config(inject_host_prefix=False))
   
   # call the api using local credentials
   response = client.list_asset_models()
   print(response)
   ```

1. 從終端機執行 **list\$1asset\$1model.py**。

   ```
   python3 list_asset_model.py
   ```

------
#### [ curl ]

**注意**  
您需要安裝 [curl](https://ec.haxx.se/install/)。

**使用 curl 取得資產模型的清單**

從終端機執行下列命令。

```
curl \
  --request GET https://$GATEWAY_HOSTNAME:443/asset-models \
  --cacert $PATH_TO_CERTIFICATE \
  --aws-sigv4 "aws:amz:edge:iotsitewise" \
  --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
  -H "x-amz-security-token:$AWS_SESSION_TOKEN"
```

回應應如下所示：

```
{
    "assetModelSummaries": [
        {
            "arn": "arn:aws:iotsitewise:{region}:{account-id}:asset-model/{asset-model-id}",
            "creationDate": 1.669245291E9,
            "description": "This is a small example asset model",
            "id": "{asset-model-id}",
            "lastUpdateDate": 1.669249038E9,
            "name": "Some Metrics Model",
            "status": {
                "error": null,
                "state": "ACTIVE"
            }
        },
        .
        .
        .
    ],
    "nextToken": null
}
```

------