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.
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
Because Microchip regularly update tools, occasionally issue(s) could be discovered while using the newer versions of the tools. If the project doesn’t 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
To 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 your AWS account, you are establishing an account to access a wide range of computing services.
Think of your AWS account as your root account for AWS services. It is very powerful and gives you complete access. Be sure to protect your username and password. You control access to your AWS account by creating individual users and groups using the Identity and Access Management (IAM) Console. You also assign policies (permissions) to the group from the IAM Console.
Create AWS account. Go to AWS website and follow instructions to create your 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 your root account against
attackers. Anyone logging in not only needs to know the password, but
also 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 your 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 your root account.
f. Create an admin IAM user AWS best practices recommend not using your 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, you’ll 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 isn’t 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 you 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
If this is the first time you are building/running this version of the demo, you must complete this step before proceeding further. Otherwise, you may skip this step.
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
If the SAM-IoT Wx v2 development board is glowing RED LED (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 ), you may skip this step.
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.
The following sections describes the steps to run the application.
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* 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.
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 & 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.
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.
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”
AWS Lambda is a service that enables code to be run in the cloud without worrying about things like 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.
we will use AWS Lambda to transfer temperature and light sensor data from SAM-IoT Development Board to cloud watch. The main concept that we will focus on is how to route data between AWS Lambda and AWS IoT Core.
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 our Lambda function to send data to the AWS IoT Core and use Amazon CloudWatch logs. We will not cover Amazon CloudWatch in this tutorial, but it could be a useful tool for debugging your application later on.
Click Next: Tags.
Click Next: Review.
Enter Lambda_IoT_role as the Role name.
Click Create role
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 we 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 we 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 also be found by selecting Functions in the menu on the left-hand side in AWS Lambda and then selecting the function from the list.
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.
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'd 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
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 : Your custom dashboard can be found in CloudWatch > Dashboards > your dash board name (here it is samiotv2_dashboard)