3.4.1 AWS Cloud IoT Core Application on SAM-IoT Wx v2 Development Board

Download

Description

The SAM-IoT Wx v2 Development board based on the SAM D21 microcontroller (MCU) is a small and easily expandable demonstration and development platform for Wi-Fi-based IoT Node applications. This specific development board can be pre-provisioned for AWS IoT Core; The application demonstrates MQTT data transfer of onboard light and temperature sensor data to AWS IoT core.

The board is referred to as SAM-IoT WA v2 Development Board when provisioned for AWS cloud IoT.

Key Highlights of SAM-IoT WA v2 Development Board

  • On-board Light and Temperature Sensors.
  • Additional sensors can be interfaced using Click Boards through an on-board mikroBUS connector.
  • On-board nEDBG debugger. Therefore, no external debugger is needed.
  • Virtual COM and USB Mass Storage for Drag and Drop programming.
  • Dual power supply options. USB or Battery.
  • On-board Li-Po battery charging circuitry.
  • ATECC608B based secure cloud connectivity
  • USB HID interface to provision the ECC608B through the SAMD21 MCU.

Features of SAM-IoT WA v2 Development Board

  • Drag and Drop of application hex files. Therefore, no need for IDE to program the SAM D21 microcontroller.
  • Microcontroller peripheral libraries and Middleware are based on the MPLAB Harmony v3 Software framework.
  • MPLAB X IDE-based project.
  • Command Line Interface (CLI) support for Wi-Fi credentials configuration.
  • 4 LED indicators to indicate the operating status.

Components Used

Software/Tools Used

This project has been verified to work with the following versions of software tools:

Refer Project Manifest present in harmony-manifest-success.yml under the project folder firmware/src/config/samd21_wa_iot_v2.

  • Refer the Release Notes to know the MPLAB X IDE and MCC Plugin version.

Because Microchip regularly updates tools, occasionally issue(s) could be discovered while using the newer versions of the tools. If the project does not seem to work and version incompatibility is suspected. It is recommended to double-check and use the same versions that the project was tested with. To download original version of MPLAB Harmony v3 packages, refer to document How to Use the MPLAB Harmony v3 Project Manifest Feature (DS90003305).

AWS Account Setup

DetailsTo run the AWS Cloud IoT core solution, an AWS account is required. The following are the steps to configure an AWS account.

Amazon Web Services (AWS) provides computing services for a fee. Some are offered for free on a trial or small-scale basis. By signing up for the AWS account, the user is establishing an account to access a wide range of computing services.

Think of the AWS account as the root account for AWS services. It is very powerful and gives the user complete access. Be sure to protect the username and password. The user controls access to the AWS account by creating individual users and groups using the Identity and Access Management (IAM) Console. The user assigns policies (permissions) to the group from the IAM Console.

Create the own AWS account
  1. Create AWS account. Go to AWS website and follow instructions to create the own AWS account. Additional details can be found at create and activate a new AWS account.
  2. Secure root account with MFA (multi-factor authentication).

    This is an important step to better secure the root account against attackers. Anyone logging in not only needs to know the password, but a constantly changing code generated by an MFA device.

    AWS recommends a number of MFA device options at the following link: https://aws.amazon.com/iam/details/mfa/.

    The quickest solution is a virtual MFA device running on a phone. These apps provide the ability to scan the QR code AWS will generate to set up the MFA device.

    a. Return to https://aws.amazon.com/ and click the Sign In to the Console.  
    b. If it asks for an IAM user name and password, select the Sign-in using root account credentials link.  
    c. Enter the email and password for the AWS account.
    d. Under Find Services search for IAM and select it to bring up the Identity and Access Management options.  
    e. Click on Activate MFA (Multi-factor Authentication) on the root account.  
    f. Create an admin IAM user AWS best practices recommend not using the root account for standard administrative tasks, but to create a special admin user for those tasks. See https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials  
    
  3. Follow the instructions at https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html for creating an admin user.
  4. Enable MFA (multi-factor authentication) for the admin user. See https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#enable-mfa-for-privileged-users
Configuring the account using CloudFormation templates

The usage of a custom PKI with TrustFLEX devices uses the Just-In-Time Registration (JITR) feature of AWS IoT Core. This feature requires a number of resources setup with an AWS account to work. The creation of these resources is automated through the AWS CloudFormation service.

  1. Sign into the AWS console using the admin user created in the previous section.
  2. Change to region to US East (Ohio) (a.k.a. us-east-2). This is done from a dropdown in the top right of the console webpage after logging in.
  3. Under Find Services search for CloudFormation and select it to bring up that service.
  4. Click Create Stack button.
  5. Select Upload a template file from the page of the stack creation.
  6. Click Choose file and upload the aws-zero-touch-full-setup.yaml file.
    Note: If running from a China region, the user will need to select the aws-zero-touch-full- setup-cn.yaml instead. These files are available in ~/.trustplatform folder.
  7. Click Next to move on to the stack details.
  8. Enter TrustFLEX as the stack name. Actual name is not important, just has to be unique.
  9. Enter a password for the user that will be created to run the demo under UserPassword.
  10. Click Next to move on to the stack options. Nothing needs to be changed here.
  11. Click Next to move on to the stack review.
  12. Check the acknowledgement box regarding IAM resources at the bottom of the page.
  13. Click Create Stack to start the resource creation.
  14. Wait until the stack creation completes. This can take a few minutes. Once done, the stack the user created will show as CREATE_COMPLETE.
  15. Save demo credentials. Click the Outputs tab for the stack to see the credentials to be saved.
  16. Save the credentials to aws_credentials.yaml file in "~/.trustplatform/aws_credentials.yaml" folder.
    Note: Indicates windows home directory is /user/username.

AWS Cloud IoT Provisioning Guide

Attention: If this is the first time the user is building/running this version of the demo, the user must complete this step before proceeding further. Otherwise, the user may skip this step.
  1. Install Trust Platform Design Suite version 2 TPDSv2.
  2. Launch Trust Platform Design Suite v2 from windows search bar, a window launches as shown below.
  3. Select Trust Platform Design Suite in webviews and Click on Usecases.
  4. In Select Security Solution, Under Use Cases select AWS IoT Authentication.
  5. Scroll Down and in Available solution by provisioning flow select AWS IoT Authentication under TrustFLEX.
  6. A Usecase gets launched. click on AWS Connect-IoT Auth-TFLEX from the Usescases.
  7. AWS Cloud Connect – IoT Authentication page launches as shown below.
  8. Scroll down and select EV62V87A Development board.
  9. Connect SAM-IoT Wx v2 Development Board to PC running Trust Platform Design Suite.
  10. Ensure MPLAB X Path is set in File -> Preference under System Settings in TPDS. This helps to program the provisioner kit firmware to the SAM-IoT Wx v2 Development Board.
  11. Scroll down to transaction diagram.
  12. Click on Icon 1 and wait till a green right mark appears.
  13. Sequentially Click on Icon 2, 3 and 4.
  14. Note the output in the output window on the right side.

ATWINC1510 Wi-Fi Controller Module Firmware and AWS Root Certificates Upgrade Guide

Attention: If the SAM-IoT Wx v2 development board is glowing RED LED (it indicates ATWINC1510 Wi-Fi controller module firmware is not up to date), follow the below steps to upgrade the ATWINC1510 firmware. Otherwise (if it glows GREEN), the user may skip this step.
  1. Click on C Source Folder in TPDS transaction diagram.
  2. In windows explorer, Application folder gets open.
  3. Click on utilities folder.
  4. Click on winc_provisioner.bat, It automatically downloads the ATWINC1510 firmware package and runs the necessary commands using the command prompt.
  5. Select the communication (COM) port identified for SAM-IoT Wx v2 development board from the drop down list and click OK.
  6. Wait till verify passed message comes up, as shown below, and then click on enter to close the command prompt; if it fails, reconnect the board and try again.

Application Demonstration

The following sections describes the steps to run the application.

  1. How to setup the SAM-IoT WA v2 Development Board
    • Connect the SAM-IoT WA v2 Development board to the host PC's USB port to power-up the board.
    • Alternatively, the board can be powered using a Li-Po battery. The board must be connected through a USB port to perform a firmware upgrade or Wi-Fi configuration.
    • Once connected to a PC, a mass storage drive icon by the name CURIOSITY will appear.
    • Drag and Drop the hex file present in the samiot2_aws_cloud_core\hex folder or use MPLAB X IDE to Program. Check section Firmware upgrade and Wi-Fi configuration process below for more detail.
    • Configure the Wi-Fi Credentials using Wi-Fi configuration through CLI method explained below.
  2. Firmware upgrade and Wi-Fi configuration process
    Firmware upgrade through TPDS and MPLAB X IDE:
    • Click on MPLAB X Project. A project opens in MPLAB X IDE. Build and program the firmware.
    Firmware upgrade through Drag and Drop:
    • Download the latest version of the hex file from the hex folder.
    • Drag and Drop the downloaded .hex file onto the CURIOSITY drive.
    • This will automatically program the microcontroller with the provided .hex file. There is no need to open the MPLAB X IDE to program the .hex file.
    Firmware upgrade through MPLAB X IDE:
    • Most developers usually follow this method to program the .hex file from the MPLAB X IDE environment.
    Wi-Fi configuration through CLI:
    • Open a terminal application on the host PC for the virtual COM port of the connected SAM-IoT WA v2 Development board, with 9600-8-None-1 settings.
    • Just enter the below command to set the Wi-Fi credentials.

      wifi < SSID >,< PASSWORD >,< SECURITY TYPE >

      Example : wifi microchip,microchip@123,2

      Note: No need of repeating this step every time while running the demo. Device remembers last used WiFi credentials and tries to connect to it. If WiFi credentials changes, this step should be performed.
  3. Running the demo application
    • If the Wi-Fi network is active, then the SAM-IoT WA v2 Development board establishes connectivity with the Wi-Fi network, sets the Blue LED, securely connects to the AWS IoT cloud, and sets the Green LED.
    • After a successful connection, the SAM-IoT WA v2 Development board pushes the real-time light and temperature sensors data to the AWS IoT cloud page and toggles the Yellow LED. If not, Red LED glows, indicating ERROR.
      Note: AWS cloud path to visualize the data pushed from the device "AWS IOT > Manage > Things > ThingNAME (ThingNAME = device_serialnumber) > classic Shadow".

The AWS Lambda Service

AWS Lambda is a service that enables code to be run in the cloud without worrying about things, such as provisioning, server management, and scalability. It natively supports many different programming languages, and interfaces with a wide range of other AWS services to facilitate cloud development.

The user will use AWS Lambda to transfer temperature and light sensor data from SAM-IoT Development Board to cloud watch. The main concept that the user will focus on is how to route data between AWS Lambda and AWS IoT Core.

  1. Sensor data is sent from connected devices to the AWS Cloud as MQTT messages.
  2. The data is forwarded from AWS IoT Core to AWS Lambda, where it is routed to cloud watch for plotting the graph.

Creating a Role in AWS IAM

  1. Sign in to the AWS Management Console and select the IAM service.
  2. Select Roles under Access Management in the menu on the left-hand side.
  3. Click Create role.
  4. Select AWS service as the trusted entity.
  5. Select Lambda as the use case.
  6. Click Next: Permissions.
  7. Attach the AWSIoTDataAccess, CloudWatchFullAccess and AWSLambdaBasicExecutionRole permission policies by using the search bar and ticking the relevant boxes. This will allow the Lambda function to send data to the AWS IoT Core and use Amazon CloudWatch logs. The user will not cover Amazon CloudWatch in this tutorial, but it could be a useful tool for debugging the application later on.
  8. Click Next: Tags.
  9. Click Next: Review.
  10. Enter Lambda_IoT_role as the Role name.
  11. Click Create role

Designing an AWS Lambda Function

Creating an empty Lambda function:

AWS Lambda is a service that enables us to run code in the cloud without worrying about server management. It can be set up to send and receive data from many different services, such as AWS IoT Core, which the user will make use of in this tutorial. To create an AWS Lambda function:

  1. Sign in to the AWS Management Console and select the Lambda service.
  2. Select Functions in the menu on the left-hand side.
  3. Click on Create function.
  4. Choose Author from scratch.
  5. Enter iot_Core_to_CwMetrics as the Function name.
  6. Select Python 3.8 as the Runtime.
  7. Expand Choose or create an execution role under Permissions and select Use an existing role.
  8. Select the Lambda_IoT_role that the user defined earlier.
  9. Click on Create function.

When the AWS Lambda function has been successfully created, the user should be redirected to the Configuration page for the iot_Core_to_CwMetrics function. This page can be found by selecting Functions in the menu on the left-hand side in AWS Lambda and then selecting the function from the list.

Triggering the Lambda Function for Relevant MQTT Packages

The next step is to configure the Lambda function to trigger when messages containing sensor data are published over MQTT in AWS IoT Core:

  1. On the Lambda function's configuration page, expand the Designer panel.
  2. Click on Add trigger.
  3. Select AWS IoT as the trigger in the dropdown menu.
  4. Select Custom IoT rule.
  5. In the Rule dropdown, select Create new rule.
  6. Enter RouteSensorData as the Rule name.
  7. Enter SELECT * FROM "$aws/things/ThingName/shadow/#" as the Rule query statement.
    Note: ThingName is the unique serial number of the device.
  8. Click Add.

Implementing the Lambda Function

  1. Ensure that the iot_Core_to_CwMetrics function is selected in the Designer panel.
  2. Paste the following Python code in the editor in the Function code panel:
     import json # Python library for dealing with JSON objects
     import boto3 # boto3 is the AWS SDK for Python
    
     cloudwatch = boto3.client('cloudwatch')
    
     #Define payload attributes that may be changed based on device message schema
     ATTRIBUTES = ['temperature','light','state','reported']
    
     # Define CloudWatch namespace
     CLOUDWATCH_NAMESPACE = "thing2/MonitorMetrics"
    
     # Define function to publish the metric data to CloudWatch
     def cw(topic, metricValue, metricName):
         metric_data = {
             'MetricName': metricName,
             'Dimensions': [{'Name': 'topic', 'Value': topic}],
             'Unit': 'None',
             'Value': metricValue,
             'StorageResolution': 1
         }
    
         cloudwatch.put_metric_data(MetricData=[metric_data],Namespace=CLOUDWATCH_NAMESPACE)
         return
    
     # Define the handler to loop through all the messages and looks to see if the message    attributes
     # include light or temp and calls the cw() function if so to publish the custom metrics    to Amazon CloudWatch
     def lambda_handler(event, context):
         my = list(event.values())
         my_list = list(my[0].values())
         print(my_list[0])
    
         for e in my_list[0]:
             print("Received a message: {}".format(str(e)))
             print(e) # Potential test point
    
             # Iterate through each attribute we would like to publish
             for attribute in ATTRIBUTES:
                 # Validate the event payload contains the desired attribute
                 if attribute  in e:
                     print("publishing {} to CloudWatch".format(attribute))
                     cw("SAM-IoT", my_list[0][attribute], attribute)
         return event
    
  3. Click Save.

Visualizing Sensor Data in Cloudwatch

  1. Search CloudWatch in AWS search box and open it.
  2. Click on Dashboard on the right side of the window under CloudWatch.
  3. Click on Create Dashboard.
  4. Enter Dashboard name as samiotv2_dashboard and click on Create Dashboard.
  5. Under Add widget Select Number.
  6. Under Add metric graph, select thing2/MonitorMetrics and then topic.
  7. Under Metrics, select BOTH SAM-IoT temperature and light metrics.
  8. Navigate to Graphed metrics and change the period to 1 second in both temperature and light metrics. Then click on Create widget.
  9. Click Save dashboard
  10. This Dashboard page refreshes every 10 seconds and update the sensor data.
    Note: The custom dashboard can be found in CloudWatch > Dashboards > the dash board name (here it is samiotv2_dashboard).

Reference

Comments