3.4.1 AWS Cloud IoT Core Application on SAM-IoT Wx v2 Development Board
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- 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.
- 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
- Follow the instructions at https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html for creating an admin user.
- 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
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.
- Sign into the AWS console using the admin user created in the previous section.
- 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.
- Under Find Services search for CloudFormation and select it to bring up that service.
- Click Create Stack button.
- Select Upload a template file from the page of the stack creation.
- 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.
- Click Next to move on to the stack details.
- Enter TrustFLEX as the stack name. Actual name is not important, just has to be unique.
- Enter a password for the user that will be created to run the demo under UserPassword.
- Click Next to move on to the stack options. Nothing needs to be changed here.
- Click Next to move on to the stack review.
- Check the acknowledgement box regarding IAM resources at the bottom of the page.
- Click Create Stack to start the resource creation.
- Wait until the stack creation completes. This can take a few minutes. Once done, the stack the user created will show as CREATE_COMPLETE.
- Save demo credentials. Click the Outputs tab for the stack to see the credentials to be saved.
- 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
- Install Trust Platform Design Suite version 2 TPDSv2.
- Launch Trust Platform Design Suite v2
from windows search bar, a window launches as shown below.
- Select Trust Platform Design
Suite in webviews and Click on Usecases.
- In Select Security Solution,
Under Use Cases select AWS IoT Authentication.
- Scroll Down and in Available
solution by provisioning flow select AWS IoT Authentication under
TrustFLEX.
- A Usecase gets launched. click on
AWS Connect-IoT Auth-TFLEX from the Usescases.
- AWS Cloud Connect – IoT Authentication
page launches as shown below.
- Scroll down and select EV62V87A
Development board.
- Connect SAM-IoT Wx v2 Development Board to PC running Trust Platform Design Suite.
- 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.
- Scroll down to transaction diagram.
- Click on Icon 1 and wait till a
green right mark appears.
- Sequentially Click on Icon 2,
3 and 4.
- Note the output in the output window on the right side.
ATWINC1510 Wi-Fi Controller Module Firmware and AWS Root Certificates Upgrade Guide
- Click on C Source Folder in TPDS
transaction diagram.
- In windows explorer, Application
folder gets open.
- Click on utilities folder.
- Click on winc_provisioner.bat,
It automatically downloads the ATWINC1510 firmware package and runs the necessary
commands using the command prompt.
- Select the communication (COM) port
identified for SAM-IoT Wx v2 development board from the drop down list and click
OK.
- 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.
- 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.
- Connect the SAM-IoT WA v2
Development board to the host PC's USB port to power-up the board.
- Firmware upgrade and Wi-Fi
configuration processFirmware upgrade through TPDS and MPLAB X IDE:Firmware upgrade through Drag and Drop:
- Click on MPLAB X Project.
A project opens in MPLAB X IDE. Build and program the firmware.
- 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.
- Most developers usually follow this method to program the .hex file from the MPLAB X IDE environment.
- 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.
- Click on MPLAB X Project.
A project opens in MPLAB X IDE. Build and program the firmware.
- 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.
- Sensor data is sent from connected devices to the AWS Cloud as MQTT messages.
- 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
- Sign in to the AWS Management Console and select the IAM service.
- Select Roles under Access Management in the menu on the left-hand side.
- Click Create role.
- Select AWS service as the trusted entity.
- Select Lambda as the use case.
- Click Next: Permissions.
- 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.
- Click Next: Tags.
- Click Next: Review.
- Enter Lambda_IoT_role as the Role name.
- 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:
- Sign in to the AWS Management Console and select the Lambda service.
- Select Functions in the menu on the left-hand side.
- Click on Create function.
- Choose Author from scratch.
- Enter iot_Core_to_CwMetrics as the Function name.
- Select Python 3.8 as the Runtime.
- Expand Choose or create an execution role under Permissions and select Use an existing role.
- Select the Lambda_IoT_role that the user defined earlier.
- 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:
- On the Lambda function's configuration page, expand the Designer panel.
- Click on Add trigger.
- Select AWS IoT as the trigger in the dropdown menu.
- Select Custom IoT rule.
- In the Rule dropdown, select Create new rule.
- Enter RouteSensorData as the Rule name.
- Enter SELECT * FROM
"$aws/things/ThingName/shadow/#" as the Rule query statement.Note: ThingName is the unique serial number of the device.
- Click Add.
Implementing the Lambda Function
- Ensure that the iot_Core_to_CwMetrics function is selected in the Designer panel.
- 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
- Click Save.
Visualizing Sensor Data in Cloudwatch
- Search CloudWatch in AWS search
box and open it.
- Click on Dashboard on the right
side of the window under CloudWatch.
- Click on Create Dashboard.
- Enter Dashboard name as
samiotv2_dashboard and click on Create Dashboard.
-
Under Add widget Select Number.
- Under Add metric graph, select
thing2/MonitorMetrics and then topic.
- Under Metrics, select BOTH
SAM-IoT temperature and light metrics.
- Navigate to Graphed metrics and
change the period to 1 second in both temperature and light metrics. Then click on
Create widget.
- Click Save dashboard
- 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
- For more details on the application usage, functionality and other details, refer to the SAM-IoT Wx v2 Development Board User Guide (DS70005506).
Comments
- This application demo builds and works
out of box by following the instructions above in Running the Demo section. If
the user needs to enhance/customize this application demo, should use the MPLAB Harmony
v3 Software framework. Refer links below to setup and build the applications using MPLAB
Harmony.
- How to Setup MPLAB Harmony v3 Software Development Framework (DS90003232).
- How to Build an Application by Adding a New PLIB, Driver, or Middleware to an Existing MPLAB Harmony v3 Project (DS90003253).
- MPLAB Harmony v3 is configurable through MPLAB Code Configurator (MCC). Refer to the below links for specific instructions to use MPLAB Harmony v3 with MCC.