

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 教程：在 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)
+ 通过 SiteWise 端口 443 访问同一网络中的 Edge 网关。
+ 安装 [OpenSSL](https://www.openssl.org/)
+ (f AWS OpsHub o AWS IoT SiteWise r) f [AWS OpsHub or AWS 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 边缘网关的 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 上运行。您可以使用 Edge 网关 AWS IoT SiteWise 或直接从 SiteWise Edge 网关获取这些证书 APIs。 AWS OpsHub 

**重要**  
凭证每 4 小时过期一次，因此您应在使用 SiteWise Edge 网关之前获取证书。 APIs 请勿将凭证缓存超过 4 小时。

### 使用 AWS OpsHub 获取临时证书 AWS IoT SiteWise
<a name="edge-apis-tutorial-temp-creds-opshub"></a>

**注意**  
您需要安装 f [AWS OpsHub o AWS IoT SiteWise r 应用程序](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)。

要使用 AWS IoT SiteWise 应用程序 AWS OpsHub 获取您的临时证书，请执行以下操作：

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 缘网关使用 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_username>` 和 `<gateway_password>` 并在终端运行 **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/)、[Boto](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 3。[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
}
```

------