本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
步骤 8:运行设备客户端脚本
在本教程中,您没有使用实际设备来报告数据。取而代之的是,你运行一个脚本来使用 CPU 和内存使用情况更新你的 Amazon IoT 设备影子,以模仿真实的传感器数据。要运行该脚本,必须先安装所需的Python软件包。在此过程中,您将安装所需的Python软件包,然后运行设备客户端脚本。
配置和运行设备客户端脚本
-
导航到 Amazon IoT 控制台
。 -
在左侧导航窗格底部,选择 设置。
-
保存您的自定义终端节点以便与设备客户端脚本一起使用。您可以使用此终端节点与事物影子进行交互。此终端节点对您在当前区域中的账户是唯一的。
您的自定义终端节点应与以下示例类似。
identifier
.iot.region
.amazonaws.com -
打开命令行并运行以下命令以导航到之前创建的教程目录。
cd iot-sitewise-rule-tutorial
-
运行以下命令来安装 Amazon IoT Device SDK for Python。
pip3 install AWSIoTPythonSDK
有关更多信息,请参阅 Amazon IoT 开发人员指南中的 Amazon IoT Device SDK for Python。
-
运行以下命令来安装 psutil,这是一个跨平台的进程和系统实用程序库。
pip3 install psutil
有关更多信息,请参阅 Python Package 索引中的 psutil
。 -
在
iot-sitewise-rule-tutorial
目录中创建一个名为thing_performance.py
的文件,然后将以下 Python 代码复制到该文件中。import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT import json import psutil import argparse import logging import time # Configures the argument parser for this program. def configureParser(): parser = argparse.ArgumentParser() parser.add_argument( "-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint", ) parser.add_argument( "-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path", ) parser.add_argument( "-c", "--cert", action="store", required=True, dest="certificatePath", help="Certificate file path", ) parser.add_argument( "-k", "--key", action="store", required=True, dest="privateKeyPath", help="Private key file path", ) parser.add_argument( "-p", "--port", action="store", dest="port", type=int, default=8883, help="Port number override", ) parser.add_argument( "-n", "--thingName", action="store", required=True, dest="thingName", help="Targeted thing name", ) parser.add_argument( "-d", "--requestDelay", action="store", dest="requestDelay", type=float, default=1, help="Time between requests (in seconds)", ) parser.add_argument( "-v", "--enableLogging", action="store_true", dest="enableLogging", help="Enable logging for the AWS IoT Device SDK for Python", ) return parser # An MQTT shadow client that uploads device performance data to AWS IoT at a regular interval. class PerformanceShadowClient: def __init__( self, thingName, host, port, rootCAPath, privateKeyPath, certificatePath, requestDelay, ): self.thingName = thingName self.host = host self.port = port self.rootCAPath = rootCAPath self.privateKeyPath = privateKeyPath self.certificatePath = certificatePath self.requestDelay = requestDelay # Updates this thing's shadow with system performance data at a regular interval. def run(self): print("Connecting MQTT client for {}...".format(self.thingName)) mqttClient = self.configureMQTTClient() mqttClient.connect() print("MQTT client for {} connected".format(self.thingName)) deviceShadowHandler = mqttClient.createShadowHandlerWithName( self.thingName, True ) print("Running performance shadow client for {}...\n".format(self.thingName)) while True: performance = self.readPerformance() print("[{}]".format(self.thingName)) print("CPU:\t{}%".format(performance["cpu"])) print("Memory:\t{}%\n".format(performance["memory"])) payload = {"state": {"reported": performance}} deviceShadowHandler.shadowUpdate( json.dumps(payload), self.shadowUpdateCallback, 5 ) time.sleep(args.requestDelay) # Configures the MQTT shadow client for this thing. def configureMQTTClient(self): mqttClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient(self.thingName) mqttClient.configureEndpoint(self.host, self.port) mqttClient.configureCredentials( self.rootCAPath, self.privateKeyPath, self.certificatePath ) mqttClient.configureAutoReconnectBackoffTime(1, 32, 20) mqttClient.configureConnectDisconnectTimeout(10) mqttClient.configureMQTTOperationTimeout(5) return mqttClient # Returns the local device's CPU usage, memory usage, and timestamp. def readPerformance(self): cpu = psutil.cpu_percent() memory = psutil.virtual_memory().percent timestamp = time.time() return {"cpu": cpu, "memory": memory, "timestamp": timestamp} # Prints the result of a shadow update call. def shadowUpdateCallback(self, payload, responseStatus, token): print("[{}]".format(self.thingName)) print("Update request {} {}\n".format(token, responseStatus)) # Configures debug logging for the AWS IoT Device SDK for Python. def configureLogging(): logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Runs the performance shadow client with user arguments. if __name__ == "__main__": parser = configureParser() args = parser.parse_args() if args.enableLogging: configureLogging() thingClient = PerformanceShadowClient( args.thingName, args.host, args.port, args.rootCAPath, args.privateKeyPath, args.certificatePath, args.requestDelay, ) thingClient.run()
-
在命令行中运行
thing_performance.py
及以下参数:-
-n
,--thingName
- 您的事物名称,例如SiteWiseTutorialDevice1
。 -
-e
,--endpoint
— 您在本过程前面保存的自定义 Amazon IoT 终端节点。 -
-r
,--rootCA
— Amazon IoT 根 CA 证书的路径。 -
-c
,--cert
— 你的 Amazon IoT 事物证书的路径。 -
-k
,--key
— 你的 Amazon IoT 东西证书私钥的路径。 -
-d
,--requestDelay
-(可选)每个设备影子更新之间等待的时间(以秒为单位)。默认值为 1 秒。 -
-v
,--enableLogging
-(可选)如果存在此参数,则脚本将从 Amazon IoT Device SDK for Python打印调试消息。
您的命令应类似于以下示例。
python3 thing_performance.py \ --thingName SiteWiseTutorialDevice1 \ --endpoint
identifier
.iot.region
.amazonaws.com \ --rootCA AmazonRootCA1.pem \ --cert device1/thing-id
-certificate.pem.crt \ --key device1/thing-id
-private.pem.key如果您正在为其他 Amazon IoT 内容运行脚本,请相应地更新事物名称和证书目录。
-
-
尝试打开和关闭设备上的程序,了解 CPU 利用率和内存使用量如何变化。脚本会打印每个 CPU 利用率和内存使用量读数。如果脚本成功将数据上传到 Device Shadow 服务,则脚本的输出应与以下示例类似。
[SiteWiseTutorialDevice1] CPU: 24.6% Memory: 85.2% [SiteWiseTutorialDevice1] Update request e6686e44-fca0-44db-aa48-3ca81726f3e3 accepted
-
请按照以下步骤操作,验证脚本是否正在更新设备影子:
-
导航到 Amazon IoT 控制台
。 -
在左侧导航窗格中选择所有设备,然后选择事物。
-
选择你的东西,SiteWiseTutorialDevice。
-
选择设备影子选项卡,选择经典影子,然后核实影子状态是否与以下示例类似。
{ "reported": { "cpu": 24.6, "memory": 85.2, "timestamp": 1579567542.2835066 } }
如果你的东西的影子状态为空或者看起来不像前面的示例,请检查脚本是否正在运行并成功连接 Amazon IoT。如果脚本在连接时继续超时 Amazon IoT,请检查您的事物策略是否已根据本教程进行配置。
-
-
请按照以下步骤操作,验证规则操作是否正在将数据发送到 Amazon IoT SiteWise:
-
在左侧导航窗格中,选择 资产。
-
选择设备队列资产 (SiteWise Tutorial Device Fleet 1 1) 旁边的箭头以展开其资产层次结构,然后选择设备资产 (SiteWise Tutorial Device 1)。
-
选择 测量值。
-
验证 最新值 单元格是否具有 CPU Usage 和 Memory Usage 属性的值。
-
如果 CPU Usage 和 Memory Usage 属性没有最新值,请刷新页面。如果在几分钟后没有显示值,请参阅排查规则问题。
-
您已完成本教程。如果要探索数据的实时可视化效果,可以在 Amazon IoT SiteWise Monitor中配置门户。有关更多信息,请参阅 使用监控数据 Amazon IoT SiteWise Monitor。否则,您可以在命令提示符下按 Ctrl+C 停止设备客户端脚本。该 Python 程序发送的消息应该不足以产生费用,但完成后最好将其停止。