Introduction

Welcome to part 2 of the Avnet Azure Sphere Starter-Kit (Out of Box Demo).  In this follow-up blog, we'll walk through connecting the example application to Azure using an IoT Hub.  After we connect our device to the IoT Hub, I'll walk through digital device twins and demonstrate how we can control devices on our board from Azure.  An finally, we'll provision a Time Series Insights resource in Azure to visualize the telemetry data that our device is sending to Azure.  

The Starter Kit is available for order here.

 

We've put together three different blogs to showcase the Avnet Azure Sphere Starter Kit and how it can be used for your next IoT project . . .

  • Blog #1: Simple non-connected demo
  • Blog #2: Hands-on connected demo using a generic IoT Hub and Time Series Insights (this blog)
    • Must complete blog 1 demo before moving on to blog 2
    • Configures IoT Hub and Time Series Insights Azure resources
    • Manipulate the device twin
    • Visualize data using Time Series Insights
  • Blog #3: Hands-on, connected demo using IoT Central
    • Must complete blog 1 before moving on to part 3
    • Walks the user though configuring a IoT Central Application to create a custom visualization and device control application

IoT Hub Application

If this is your first time working with one of the cloud providers, don’t worry.  While Azure has hundreds of different resources you can utilize, we’re only going to need a couple of things.  I’ll walk us through all the details, it’s not as hard as you may think.

Before we begin, I’ll make the assumption that you’ve completed the simplified non-connected example.  If not, please go back and complete that tutorial hereFor the IoT Hub tutorial the following prerequisites are required.

  • Visual Studio and the Azure Sphere SDK are installed and confirmed working
  • You were able to run the non-connected example without any issues (link)
  • Your device is connected to a Wi-Fi access point and has access to the internet
    • Help with WI-FI connections (link)
  • You have an Azure account.
    • You can sign up for a free Azure account here.

 

Create an IoT Hub

The first thing we need to do is create an IoT Hub.  The IoT Hub is a collection point for IoT devices connecting into Azure.  Once a device is connected to an IoT Hub and streaming telemetry data, other Azure services can ingest the data and do meaningful things.  Azure IoT Hubs can manage connections to hundreds of thousands of devices. 

  • Log into Azure https://portal.azure.com
  • Click on “+ Create a resource” à “Internet of Things” à “IoT Hub.”  The IoT hub form will open.
    • You can also use the search bar to search for "IoT Hub."

  • In the IoT hub form fill in each entry
    • Subscription: Whatever your subscription is, it may be a “Free” or “Pay-as-you-Go” subscription.
    • Resource Group: Click on the “Create new” link under the entry box and give your new Resource Group a name.  For example “DemoRG”. 
    • Region: Select the region closest to your physical location.
    • IoT Hub Name: Select a name for your IoT Hub. Note that the IoT Hub name must be unique across all of Azure.  Your entry will be validated and if the name you used is not available, the form will display an error.  Azure will generate a FQDN for your IoT Hub, so it must be unique.
  • Click on the “Review + create” button

  • Review the properties for your new IoT Hub.  The “Pricing and scale tier” should be set to S1, the default.  This tier will accommodate 400,000 data messages/day to/from your Azure Sphere device.  After you’re happy with the properties, click on the “Create” button at the bottom of the form.

  • Azure will start to work on deploying your IoT Hub.  This can take a few minutes.  You can monitor the progress/status of your deployment by clicking on the bell icon in the header.


 

                      

Create an IoT device

When your IoT Hub deployment finishes (mine took ~3 ½ minutes), navigate to your new IoT Hub.  There are multiple ways to get to your new IoT Hub.

  • From the notification message (Bell Icon) click the “Go to resource” button
  • From the left most side of the Azure interface, click on “Resource groups” à <your resource group name> à <your IoT Hub name>

Now find the “IoT devices” blade, I had to scroll down the list.  Click on the “IoT devices” then click the “+ Add” button at the top of the form.

  • Give your device a “Device ID.”  The Device ID can be characters and/or numbers.  Accept all the defaults for "Authentication type" and leave the “Auto-generate keys” box checked.  After reviewing the settings click the “Save” button at the bottom of the form.

  • You’ll see your device added to the list, go ahead and click on your device.  This opens the “Device details” form.  Now copy the “Connection string (primary key)” text.  There’s a copy button at the right side of the text.  We’ll use this in the Azure Sphere application so that our device can connect to our IoT Hub and specifically connect as the new IoT device we just added.
    • My Connection String: HostName=BWDemoIOTHub.azure-devices.net;DeviceId=AvnetStarterKit;SharedAccessKey=83II1vxvdGmwexCM18jEhY1RxTWJSJXRMbqxEgdwj/Q=

A quick note about provisioning IoT devices in Azure.  In this example we’re using a connection string to connect to Azure.  The advantage of using this method is that it’s simple and quick to setup, and the name of your device can be whatever you want it to be.  The disadvantage of using the connection string method is that it does not scale. If you have 3 devices all running the same base firmware you would need 3 separate builds, each with a unique connection string.  That’s almost manageable, but what if you have 50, or 100, or 200,000 devices, you see where I’m going, not manageable at all!

To deploy devices at scale, Azure provides a Device Provisioning Service, or DPS.  Using the DPS method, all 200,000 devices would use the exact same firmware build, and when they first connect to Azure, they are automatically provisioned to an IoT Hub.  You can read more about DPS and Azure Sphere here

For development, DPS adds setup time overhead.  Additionally, when devices are provisioned to the IoT Hub using DPS the Device ID is the unique ID for each device i.e., “7533EFAB4A0552823683E962E153841CC6DC59AA714D372C946472B038971CECB305E63D5837AD2AA1968CD51AB1C0FA584A85CF9AB4D6956A50D024A32B7009.”  Not a user friendly device ID.

Modify the Azure Sphere source code

Now let’s go back to Visual Studio.  If it’s not open, go ahead and launch the Visual Studio application and open the “AvnetStarterKitReferenceDesign” project.  Visual Studio keeps a list of recent projects, your project should be found in that list.

Remember in the simple non-connected application we discussed the three different build configurations:

  1. No cloud connectivity.  This is the simplest configuration.  The application runs and you can monitor sensor data from the Visual Studio debug window.
  2. IoT Hub connectivity.  This configuration requires an Azure IoT Hub and an IoT Hub connection string.  Once we have the Hub configured and the application connecting to the IoT Hub, we’ll walk through how to provision a Time Series Insights (TSI) application to visualize the sensor data and control GPIOs on the board from the cloud.
  3. IoT Central connectivity.  This configuration leverages Microsoft’s IoT Central SaaS product.  IoT Central provides a simple interface that allows users to visualize telemetry and to control connected devices.

For this example we’ll enable the IoT Hub Connectivity configuration.

  • Open the build_options.h file
  • On about line #8 remove the “//” comment characters to enable the #define IOT_HUB_APPLICATION configuration.  Save your work by typing (Ctrl+S).

Next we need to hardcode the connection string for out IoT device.

    • Open connection_strings.h and paste your connection string inside the “”.  The entry in my file looks like this:

// Define your connection string here.  The connection string is required to connect to Azure.

#define MY_CONNECTION_STRING "HostName=BWDemoIOTHub.azure-devices.net;DeviceId=AvnetStarterKit;SharedAccessKey=83II1vxvdGmwexCM18jEhY1RxTWJSJXRMbqxEgdwj/Q="

    • Save your work by typing (Ctrl+S)

 

Next we need to inform the Azure Sphere OS that we intend to connect to an external server.  Remember in the first blog I stated that the Azure Sphere device is locked down?  Well here’s a case where the device needs explicit permission to connect to a specific external server.  If you don’t tell the OS about external servers you want to connect to, then the OS will not allow any traffic to your server.  Take a look at our connection string. Notice that the first part of the string contains a FQDN hostname, in my case, the hostname is “BWDemoIOTHub.azure-devices.net.” 

  • Open the app_manifest.json file.  This file is located outside the other folders in your Solution Explorer window, usually at the very bottom of the list.
  • Find the “AllowedConnections” entry and paste the hostname from your connection string into the field with a set of “” around the text.
  • Save your work by typing (Ctrl+S).

To review.  The modifications we made to the source code . . .

  1. We enabled the IOT_HUB_APPLICATION define in build_options.h
  2. We added our connection string to the connection_strings.h file
  3. We added our hostname string to the “AllowedConnection” entry in the app_manifest.json file

We should be ready to build the IoT Hub configuration!

Build and run the application

To compile, link and load the application onto your Starter Kit, you just need to click on the “Remote GDB Debugger” button in the toolbar.  If you're asked to save the changes click "OK."

You’ll see the build process run and a popup box stating that Visual Studio is starting the application. If you look at the output window, you should see something similar to the text below.

Let's review this output . . .

Updating device twin:

This output is showing that the application is sending device twin updates.  You can see in the output that these updates are sent as JSON {key: value} pairs.  These {key: value} pairs do NOT need to be predefined in Azure.  As we’ll see shortly, if you send valid JSON {key: value} pairs these objects will be populated in the device twin for our device.

IOTHUB_CLIENT_CONNECTION_OK

This output shows that our device has connected to our IoT Hub.  If you see other messages, verify that your device has a Wi-Fi connection (> azsphere device wifi show-status), and that you correctly included the connection string for your IoT Hub in the Visual Studio project.

Sending telemetry:

This output shows the telemetry data we’re sending to Azure.  As with the device twin update message, we’re sending JSON key: value pairs. To send telemetry, you just need a valid JSON structure.  The IoT Hub will collect this data and simply pass it on to any services that subscribe to the IoT Hub. 

Device Twins

Device Twins are a digital representation of the device state that lives in Azure.  You can look at the device twin for your device in Azure. Detailed device twin documentation can be reviewed here

  • If you still have your IoT device open, you'll need to click on the "Refresh" link to see the Device Twin link.
  • If you don't still have your IoT device open . . .
    • Navigate to your IoT Hub (1)
    • Find and click on the “IoT devices” blade (2)
    • Click on your device (3)

This page should look familiar.  This is where we found our connection string.  This time we’re going to click on the “Device twin” link.

The Device Twin page opens up and displays a scrolling window with the contents of our device twin.

A few things I want to point out here.

  • Notice the information bar stating that we can modify the device twin from this interface.
  • Desired properties.  This object is currently empty, but we can add desired properties and Azure will send C2D messages to our application with the desired {key: value} pairs.  More on this soon.
  • Reported object. This JSON object has all the device twin properties that our application sent up on startup.  Remember we did not do anything special on the Azure side to pre-define these properties.  Our application sent them up, and Azure populated them into our device twin. 

The reported properties is a cool feature.  For instance, we sent up the “versionString.”  This could be used when managing a large number of devices to make sure all devices in the field are running the correct application version.

Desired Properties

The desired properties are used to communicate to our device that we want to change something or set some state.  In our software application we have already defined a list of desired properties.  For each of these properties we take some kind of an action.  Here’s a list of the desired properties implemented in the application.  Review device_twin.c for all the dirty details.

Key

Value

 

userLedRed

true | false

enables/disables the red LED of the user RGB LED

userLedGreen

true | false

enables/disables the green LED of the user RGB LED

userLedBlue

true | false

enables/disables the blue LED of the user RGB LED

appLed

true | false

enables/disables the application LED

wifiLed

true | false

enables/disables the WI-FI LED

clickBoardRelay1

true | false

enables/disables relay #1 on a Relay Click board if installed in Click Module socket #1

clickBoardRelay2

true | false

enables/disables relay #2 on a Relay Click board if installed in Click Module socket #1

 

So how do we use these desired properties to change something on the board.  It’s easy, we simply add a new key: value pair to the desired properties section of the device twin.

  • Make sure your application is running on your Avnet Starter Kit
  • In Azure you should still have the device twin page open, if not open it now
  • In the desired object add a new line and enter "userLedBlue": true,
  • Click on the “Save” link at the top of the form

  • When you clicked “Save” Azure sent down a desired properties message to our device with the key value pair {“userLedBlue”: true}.  You should also see debug in Visual Studio

Received device update. New userLedBlue is true

[MCU] Updating device twin: {"userLedBlue": true}

  • The application received this message, parsed out the key “userLedBlue”, looked up what to do with that key, pulled the value out of the message and, in this case, toggled a GPIO pin connected to the Blue LED of the user LED!  Pretty cool!
  • Back in Azure, click on the “Refresh” button to refresh the device twin, and notice that there is a new entry called “userLedBlue”

I invite you to play with some more of the desired properties detailed in the table above. They will all behave the same way. Note that if you want to use the clickBoardRelay1, and clickBoardRelay2 properties, you’ll need to purchase a Relay Click and insert it into mikroBUS socket #1.

 

 

  Did you know?
  • Click Boards
    • There are over 650 different Click Boards available that can be used on the Avnet Starter Kit

 

 

Time Series Insights

Our application is also streaming lots of telemetry data.  What can we do in Azure to view this data?  One answer is to setup a Time Series Insights (TSI) environment.  TSI documentation is here.  There are other services available in Azure to visualize your data, TSI is easy to setup and is a powerful tool.

“Azure Time Series Insights provides powerful data exploration and telemetry tools to help you refine operational analysis.”

  • Login to your Azure account: https://portal.azure.com
  • Click on the “+ Create a resource” link (1)
  • Click on the “Internet of Things” category (2)
  • Click on the “Time Series Insights” link (3)

 

On the “Basics” Tab fill in the form

  • Enter a name for your TSI environment
  • Select your Subscription
  • Select the same Resource Group you used for the IoT Hub
  • Select the Location closest to your physical location

 

Next click on the “Event Source” tab.

  • Name: Select a name for your event
  • Source Type: Select “IoT Hub”
  • Select a Hub: Select “Select existing”
  • Subscription: Select your subscription
  • IoT Hub Name: Select the name of your IoT Hub from the list
  • IoT Hub access policy name: Select “iothubowner”
  • IoT Hub consumer group: Select “$Default”
  • Click on “Review + create”

On the “Review + Create” screen, review your settings and if they look good, click on the “Create” button at the bottom of the form.

You’ll see your TSI environment being provisioned:

 

Once your deployment is complete (mine took 42 seconds), navigate to your new TSI resource. 

  • From the left most column, click on “Resource Groups”
  • Select your resource group
  • Select your TSI Environment

  • Click on the “Go to Environment” link

The Environment will open, but you won’t see any data

Select the “Events” pull down menu.  You’ll see entries for all the different telemetry items the application sends up, select the “gX” entry.  You can add additional measurements to the graph by clicking the “Add” button.  The graphic below shows the gX, gY, and gZ data all plotted.  I was moving my Starter Kit around on the different axis’s to generate this data.

Clean up the resources

When you’re finished playing with the graph and the demo, you should delete the Azure resources.  If you don’t delete them, then you’ll see monthly charges for the IoT Hub, and for the Time Series Insights resources.  The quick and easy way to remove all these resources is to delete the Resource Group.

  • Open the Azure Portal: https://portal.azure.com
  • In the left most column, select “Resource Groups”
  • Select your resource group
  • At the top select “Delete resource group”

  • Type the name of your resource group into the form
  • Click on the “Delete” button at the bottom of the form.

Review

In this demo we learned . . .

  1. How to setup an IoT Hub
  2. How to manually add an IoT device to the Hub
  3. How to configure the Azure Sphere demo application to connect to the IoT Hub
  4. How to view the Device Twin for our device
  5. How to modify the Device Twin
  6. How to setup Time Series Insights (TSI)
  7. How to view our data in TSI
  8. How to clean up our Azure resources

The last blog entry in this series will walk you through how to setup an IoT Central Application to work with the Starter Kit example project.