View a markdown version of this page

教學課程:列出 AWS IoT SiteWiseEdge 閘道上的資產模型 - AWS IoT SiteWise

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

教學課程:列出 AWS IoT SiteWiseEdge 閘道上的資產模型

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

先決條件

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

為了完成本教學,您需要以下項目:

步驟 1:取得 SiteWise Edge 閘道服務簽署的憑證

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

OpenSSL
注意

您需要安裝 OpenSSL 才能執行此命令。

開啟終端機並執行下列命令,從 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 OpsHubforAWS IoT SiteWise

您可以使用 AWS OpsHubAWS IoT SiteWise。如需詳細資訊,請參閱管理 SiteWise Edge 閘道。

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

export PATH_TO_CERTIFICATE='<absolute_path_to_certificate>'

步驟 2:取得 SiteWise Edge 閘道主機名稱

注意

您需要安裝 OpenSSL 才能執行此命令。

若要完成教學課程,您需要 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 閘道的臨時登入資料

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

重要

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

使用 取得暫時登入AWS OpsHub資料AWS IoT SiteWise

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

  1. 登入應用程式。

  2. 選擇設定。

  3. 針對身分驗證,選擇複製登入資料。

  4. 展開適合您環境的選項,然後選擇複製。

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

使用 SiteWise Edge 閘道 API 取得臨時憑證

若要使用 SiteWise Edge 閘道 API 取得您可以使用 Python 指令碼或 curl 的臨時登入資料,您必須先擁有 SiteWise Edge 閘道的使用者名稱和密碼。SiteWise Edge 閘道使用 SigV4 身分驗證和授權。如需新增使用者的詳細資訊,請參閱 LDAP 或 Linux 使用者集區。這些登入資料將用於下列步驟,以在 SiteWise Edge 閘道上取得使用 AWS IoT SiteWiseAPIs。

Python
注意

您需要安裝 urllib3 和 Python3。

使用 Python 取得登入資料
  1. 建立名為 get_credentials.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 theAWS IoT SiteWiseEdge 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:])
  2. 從終端機使用您建立<gateway_password>的登入資料取代 <gateway_username>和 ,執行 get_credentials.py。

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

您需要安裝 curl。

使用 curl 取得登入資料
  1. 從終端機執行下列命令,將 <gateway_username> 和 <gateway_password> 取代為您建立的登入資料。

    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" }
  2. 從您的終端機中執行下列命令。

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

步驟 4:取得 SiteWise Edge 閘道上的資產模型清單

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

Python
注意

您需要安裝 Python3、Boto3 和 BotoCore。

使用 Python 取得資產模型的清單
  1. 建立名為 list_asset_model.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)
  2. 從終端機執行 list_asset_model.py。

    python3 list_asset_model.py
curl
注意

您需要安裝 curl。

使用 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 }