Step 8: Running the device client script - Amazon IoT SiteWise
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Step 8: Running the device client script

For this tutorial, you aren't using an actual device to report data. Instead, you run a script to update your Amazon IoT thing's device shadow with CPU and memory usage to imitate real sensor data. To run the script, you must first install required Python packages. In this procedure, you install the required Python packages and then run the device client script.

To configure and run the device client script
  1. Navigate to the Amazon IoT console.

  2. At the bottom of the left navigation pane, choose Settings.

  3. Save your custom endpoint for use with the device client script. You use this endpoint to interact with your thing's shadows. This endpoint is unique to your account in the current Region.

    Your custom endpoint should look like the following example.

    identifier.iot.region.amazonaws.com
  4. Open a command line and run the following command to navigate to the tutorial directory you created earlier.

    cd iot-sitewise-rule-tutorial
  5. Run the following command to install the Amazon IoT Device SDK for Python.

    pip3 install AWSIoTPythonSDK

    For more information, see Amazon IoT Device SDK for Python in the Amazon IoT Developer Guide

  6. Run the following command to install psutil, a cross-platform process and system utilities library.

    pip3 install psutil

    For more information, see psutil in the Python Package Index.

  7. Create a file called thing_performance.py in the iot-sitewise-rule-tutorial directory and then copy the following Python code into the file.

    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. Run thing_performance.py from the command line with the following parameters:

    • -n, --thingName – Your thing name, such as SiteWiseTutorialDevice1.

    • -e, --endpoint – Your custom Amazon IoT endpoint that you saved earlier in this procedure.

    • -r, --rootCA – The path to your Amazon IoT root CA certificate.

    • -c, --cert – The path to your Amazon IoT thing certificate.

    • -k, --key – The path to your Amazon IoT thing certificate private key.

    • -d, --requestDelay – (Optional) The time in seconds to wait between each device shadow update. Defaults to 1 second.

    • -v, --enableLogging – (Optional) If this parameter is present, the script prints debug messages from the Amazon IoT Device SDK for Python.

    Your command should look similar to the following example.

    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

    If you're running the script for additional Amazon IoT things, update the thing name and certificate directory accordingly.

  9. Try opening and closing programs on your device to see how the CPU and memory usages change. The script prints each CPU and memory usage reading. If the script uploads data to the device shadow service successfully, the script's output should look like the following example.

    [SiteWiseTutorialDevice1] CPU: 24.6% Memory: 85.2% [SiteWiseTutorialDevice1] Update request e6686e44-fca0-44db-aa48-3ca81726f3e3 accepted
  10. Follow these steps to verify that the script is updating the device shadow:

    1. Navigate to the Amazon IoT console.

    2. In the left navigation pane, choose All devices and then choose Things.

    3. Choose your thing, SiteWiseTutorialDevice.

    4. Choose the Device Shadows tab, choose Classic Shadow, and verify that the Shadow state looks like the following example.

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

      If your thing's shadow state is empty or doesn't look like the previous example, check that the script is running and successfully connected to Amazon IoT. If the script continues to time out when connecting to Amazon IoT, check that your thing policy is configured according to this tutorial.

  11. Follow these steps to verify that the rule action is sending data to Amazon IoT SiteWise:

    1. Navigate to the Amazon IoT SiteWise console.

    2. In the left navigation pane, choose Assets.

    3. Choose the arrow next to your device fleet asset (SiteWise Tutorial Device Fleet 1 1) to expand its asset hierarchy, and then choose your device asset (SiteWise Tutorial Device 1).

    4. Choose Measurements.

    5. Verify that the Latest value cells have values for the CPU Usage and Memory Usage properties.

      
              Screenshot with "Measurements" highlighted.
    6. If the CPU Usage and Memory Usage properties don't have the latest values, refresh the page. If values don't appear after a few minutes, see Troubleshooting a rule.

  12. You have completed this tutorial. If you want to explore live visualizations of your data, you can configure a portal in Amazon IoT SiteWise Monitor. For more information, see Monitoring data with Amazon IoT SiteWise Monitor. Otherwise, you can press CTRL+C in your command prompt to stop the device client script. It's unlikely the Python program will send enough messages to incur charges, but it's a best practice to stop the program when you're done.