步骤 8:运行设备客户端脚本 - Amazon IoT SiteWise
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

步骤 8:运行设备客户端脚本

在本教程中,您没有使用实际设备来报告数据。取而代之的是,你运行一个脚本来使用 CPU 和内存使用情况更新你的 Amazon IoT 设备影子,以模仿真实的传感器数据。要运行该脚本,必须先安装所需的Python软件包。在此过程中,您将安装所需的Python软件包,然后运行设备客户端脚本。

配置和运行设备客户端脚本
  1. 导航到 Amazon IoT 控制台

  2. 在左侧导航窗格底部,选择 设置

  3. 保存您的自定义终端节点以便与设备客户端脚本一起使用。您可以使用此终端节点与事物影子进行交互。此终端节点对您在当前区域中的账户是唯一的。

    您的自定义终端节点应与以下示例类似。

    identifier.iot.region.amazonaws.com
  4. 打开命令行并运行以下命令以导航到之前创建的教程目录。

    cd iot-sitewise-rule-tutorial
  5. 运行以下命令来安装 Amazon IoT Device SDK for Python。

    pip3 install AWSIoTPythonSDK

    有关更多信息,请参阅 Amazon IoT 开发人员指南中的 Amazon IoT Device SDK for Python

  6. 运行以下命令来安装 psutil,这是一个跨平台的进程和系统实用程序库。

    pip3 install psutil

    有关更多信息,请参阅 Python Package 索引中的 psutil

  7. 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()
  8. 在命令行中运行 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 内容运行脚本,请相应地更新事物名称和证书目录。

  9. 尝试打开和关闭设备上的程序,了解 CPU 利用率和内存使用量如何变化。脚本会打印每个 CPU 利用率和内存使用量读数。如果脚本成功将数据上传到 Device Shadow 服务,则脚本的输出应与以下示例类似。

    [SiteWiseTutorialDevice1] CPU: 24.6% Memory: 85.2% [SiteWiseTutorialDevice1] Update request e6686e44-fca0-44db-aa48-3ca81726f3e3 accepted
  10. 请按照以下步骤操作,验证脚本是否正在更新设备影子:

    1. 导航到 Amazon IoT 控制台

    2. 在左侧导航窗格中选择所有设备,然后选择事物

    3. 选择你的东西,SiteWiseTutorialDevice

    4. 选择设备影子选项卡,选择经典影子,然后核实影子状态是否与以下示例类似。

      { "reported": { "cpu": 24.6, "memory": 85.2, "timestamp": 1579567542.2835066 } }

      如果你的东西的影子状态为空或者看起来不像前面的示例,请检查脚本是否正在运行并成功连接 Amazon IoT。如果脚本在连接时继续超时 Amazon IoT,请检查您的事物策略是否已根据本教程进行配置。

  11. 请按照以下步骤操作,验证规则操作是否正在将数据发送到 Amazon IoT SiteWise:

    1. 导航到 Amazon IoT SiteWise 控制台

    2. 在左侧导航窗格中,选择 资产

    3. 选择设备队列资产 (SiteWise Tutorial Device Fleet 1 1) 旁边的箭头以展开其资产层次结构,然后选择设备资产 (SiteWise Tutorial Device 1)。

    4. 选择 测量值

    5. 验证 最新值 单元格是否具有 CPU UsageMemory Usage 属性的值。

      
              屏幕截图中突出显示 “测量”。
    6. 如果 CPU UsageMemory Usage 属性没有最新值,请刷新页面。如果在几分钟后没有显示值,请参阅排查规则问题

  12. 您已完成本教程。如果要探索数据的实时可视化效果,可以在 Amazon IoT SiteWise Monitor中配置门户。有关更多信息,请参阅 使用监控数据 Amazon IoT SiteWise Monitor。否则,您可以在命令提示符下按 Ctrl+C 停止设备客户端脚本。该 Python 程序发送的消息应该不足以产生费用,但完成后最好将其停止。